################################################################################
## setup
################################################################################
# clean slate
rm(list = ls())
date()

# load packages
pkg <- c("foreign", 
         "countrycode",
         "tidyverse", 
         "gridExtra", 
         "scales", 
         "RColorBrewer", 
         "lfe", 
         "lme4", 
         "multcomp", 
         "grid", 
         "stargazer")
lapply(pkg, require, character.only = TRUE)

# set directory
MAIN_DIR <- "~/Dropbox/Research/controls/replication/"

# load data
load(file = paste(MAIN_DIR, "data-merge.RData", sep = ""))
load(file = paste(MAIN_DIR, "ratings-merge.RData", sep = ""))


################################################################################
## set up variable names
################################################################################
# set var and var name correspondence
var.df <- tibble(var = c("ln_ave_arimanpf_lag",
                         
                         "geodist_kai_tercile_low",
                         "geodist_kai_tercile_med",
                         "geodist_kai_tercile_high",
                         "msci_kai_tercile_low",
                         "msci_kai_tercile_med",
                         "msci_kai_tercile_high",
                         "fitch_kai_tercile_low",
                         "fitch_kai_tercile_med",
                         "fitch_kai_tercile_high",
                         
                         "geodist_kao_tercile_low",
                         "geodist_kao_tercile_med",
                         "geodist_kao_tercile_high",
                         "msci_kao_tercile_low",
                         "msci_kao_tercile_med",
                         "msci_kao_tercile_high",
                         "fitch_kao_tercile_low",
                         "fitch_kao_tercile_med",
                         "fitch_kao_tercile_high",
                         "dpi_kao_tercile_low",
                         "dpi_kao_tercile_med",
                         "dpi_kao_tercile_high",
                         
                         "geodist_kao_short_tercile_low",
                         "geodist_kao_short_tercile_med",
                         "geodist_kao_short_tercile_high",
                         "msci_kao_short_tercile_low",
                         "msci_kao_short_tercile_med",
                         "msci_kao_short_tercile_high",
                         "fitch_kao_short_tercile_low",
                         "fitch_kao_short_tercile_med",
                         "fitch_kao_short_tercile_high",
                         
                         "fedrate_high",
                         "vix_high",
                         
                         "wld_kao_tercile_low",
                         "wld_kao_tercile_med",
                         "top_kao_tercile_low",
                         "top_kao_tercile_med",
                         
                         "sl_geodist_imf",
                         "msci_mean_imf_lag",
                         "sl_fitch_imf",
                         "sl_geodist_crisis2",
                         "msci_mean_crisis2_lag",
                         "sl_fitch_crisis2",
                         "sl_geodist_bank_crisis",
                         "msci_mean_bank_crisis_lag",
                         "sl_fitch_bank_crisis",
                         
                         "ln_ave_arimanpf_lag:geodist_kai_tercile_low",
                         "ln_ave_arimanpf_lag:geodist_kai_tercile_med",
                         "ln_ave_arimanpf_lag:geodist_kai_tercile_high",
                         "ln_ave_arimanpf_lag:msci_kai_tercile_low",
                         "ln_ave_arimanpf_lag:msci_kai_tercile_med",
                         "ln_ave_arimanpf_lag:msci_kai_tercile_high",
                         "ln_ave_arimanpf_lag:fitch_kai_tercile_low",
                         "ln_ave_arimanpf_lag:fitch_kai_tercile_med",
                         "ln_ave_arimanpf_lag:fitch_kai_tercile_high",
                         
                         "ln_ave_arimanpf_lag:geodist_kao_tercile_low",
                         "ln_ave_arimanpf_lag:geodist_kao_tercile_med",
                         "ln_ave_arimanpf_lag:geodist_kao_tercile_high",
                         "ln_ave_arimanpf_lag:msci_kao_tercile_low",
                         "ln_ave_arimanpf_lag:msci_kao_tercile_med",
                         "ln_ave_arimanpf_lag:msci_kao_tercile_high",
                         "ln_ave_arimanpf_lag:fitch_kao_tercile_low",
                         "ln_ave_arimanpf_lag:fitch_kao_tercile_med",
                         "ln_ave_arimanpf_lag:fitch_kao_tercile_high",
                         "ln_ave_arimanpf_lag:dpi_kao_tercile_low",
                         "ln_ave_arimanpf_lag:dpi_kao_tercile_med",
                         "ln_ave_arimanpf_lag:dpi_kao_tercile_high",
                         
                         "ln_ave_arimanpf_lag:geodist_kao_short_tercile_low",
                         "ln_ave_arimanpf_lag:geodist_kao_short_tercile_med",
                         "ln_ave_arimanpf_lag:geodist_kao_short_tercile_high",
                         "ln_ave_arimanpf_lag:msci_kao_short_tercile_low",
                         "ln_ave_arimanpf_lag:msci_kao_short_tercile_med",
                         "ln_ave_arimanpf_lag:msci_kao_short_tercile_high",
                         "ln_ave_arimanpf_lag:fitch_kao_short_tercile_low",
                         "ln_ave_arimanpf_lag:fitch_kao_short_tercile_med",
                         "ln_ave_arimanpf_lag:fitch_kao_short_tercile_high",
                         
                         "ln_ave_arimanpf_lag:fedrate_high",
                         "geodist_kao_tercile_med:fedrate_high",
                         "geodist_kao_tercile_high:fedrate_high",
                         "msci_kao_tercile_med:fedrate_high",
                         "msci_kao_tercile_high:fedrate_high",
                         "fitch_kao_tercile_med:fedrate_high",
                         "fitch_kao_tercile_high:fedrate_high",
                         
                         "ln_ave_arimanpf_lag:vix_high",
                         "geodist_kao_tercile_med:vix_high",
                         "geodist_kao_tercile_high:vix_high",
                         "msci_kao_tercile_med:vix_high",
                         "msci_kao_tercile_high:vix_high",
                         "fitch_kao_tercile_med:vix_high",
                         "fitch_kao_tercile_high:vix_high",
                         
                         "ln_ave_arimanpf_lag:wld_kao_tercile_low",
                         "ln_ave_arimanpf_lag:wld_kao_tercile_med",
                         "ln_ave_arimanpf_lag:top_kao_tercile_low",
                         "ln_ave_arimanpf_lag:top_kao_tercile_med",
                         
                         "ln_ave_arimanpf_lag:geodist_kao_tercile_med:fedrate_high",
                         "ln_ave_arimanpf_lag:geodist_kao_tercile_high:fedrate_high",
                         "ln_ave_arimanpf_lag:msci_kao_tercile_med:fedrate_high",
                         "ln_ave_arimanpf_lag:msci_kao_tercile_high:fedrate_high",
                         "ln_ave_arimanpf_lag:fitch_kao_tercile_med:fedrate_high",
                         "ln_ave_arimanpf_lag:fitch_kao_tercile_high:fedrate_high",
                         
                         "ln_ave_arimanpf_lag:geodist_kao_tercile_med:vix_high",
                         "ln_ave_arimanpf_lag:geodist_kao_tercile_high:vix_high",
                         "ln_ave_arimanpf_lag:msci_kao_tercile_med:vix_high",
                         "ln_ave_arimanpf_lag:msci_kao_tercile_high:vix_high",
                         "ln_ave_arimanpf_lag:fitch_kao_tercile_med:vix_high",
                         "ln_ave_arimanpf_lag:fitch_kao_tercile_high:vix_high",
                         
                         "real_interest_rate_lag",
                         "inflation_lag",
                         "reserves_imports_lag",
                         "log(trade_open_lag)",
                         "crisis2_lag",
                         "imf_program_lag",
                         "bank_crisis_lag",
                         "log(gdp_const_lag)",
                         "log(gdp_pc_const_lag)",
                         "peg_lag",
                         "polity2_lag",
                         "bits_with_usa",
                         "port_inv_net_lag",
                         "poco_eu_fsu",
                         "exec_rc_lag",
                         "checks_lag"),
                 var_name = c("Log Volatility (ARIMA, lag, baseline)",
                              
                              "Mean KAI: Geographic Peers (low, spatial lag)",
                              "Mean KAI: Geographic Peers (medium, spatial lag)",
                              "Mean KAI: Geographic Peers (high, spatial lag)",
                              "Mean KAI: MSCI Peers (low, spatial lag)",
                              "Mean KAI: MSCI Peers (medium, spatial lag)",
                              "Mean KAI: MSCI Peers (high, spatial lag)",
                              "Mean KAI: Ratings Peers (low, spatial lag)",
                              "Mean KAI: Ratings Peers (medium, spatial lag)",
                              "Mean KAI: Ratings Peers (high, spatial lag)",
                              
                              "Mean KAO: Geographic Peers (low, spatial lag)",
                              "Mean KAO: Geographic Peers (medium, spatial lag)",
                              "Mean KAO: Geographic Peers (high, spatial lag)",
                              "Mean KAO: MSCI Peers (low, spatial lag)",
                              "Mean KAO: MSCI Peers (medium, spatial lag)",
                              "Mean KAO: MSCI Peers (high, spatial lag)",
                              "Mean KAO: Ratings Peers (low, spatial lag)",
                              "Mean KAO: Ratings Peers (medium, spatial lag)",
                              "Mean KAO: Ratings Peers (high, spatial lag)",
                              "Mean KAO: Partisanship Peers (low, spatial lag)",
                              "Mean KAO: Partisanship Peers (medium, spatial lag)",
                              "Mean KAO: Partisanship Peers (high, spatial lag)",
                              
                              "Mean KAO (short): Geographic Peers (low, spatial lag)",
                              "Mean KAO (short): Geographic Peers (medium, spatial lag)",
                              "Mean KAO (short): Geographic Peers (high, spatial lag)",
                              "Mean KAO (short): MSCI Peers (low, spatial lag)",
                              "Mean KAO (short): MSCI Peers (medium, spatial lag)",
                              "Mean KAO (short): MSCI Peers (high, spatial lag)",
                              "Mean KAO (short): Ratings Peers (low, spatial lag)",
                              "Mean KAO (short): Ratings Peers (medium, spatial lag)",
                              "Mean KAO (short): Ratings Peers (high, spatial lag)",
                              
                              "Effective Federal Funds Rate (high)",
                              "VIX Index (high)",
                              
                              "Mean KAO: Global (low, lag)",
                              "Mean KAO: Global (medium, lag)",
                              "Mean KAO: Top Growth Countries (low, lag)",
                              "Mean KAO: Top Growth Countries (medium, lag)",
                              
                              "Mean IMF Program: Geographic Peers (spatial lag)",
                              "Mean IMF Program: MSCI Peers (spatial lag)",
                              "Mean IMF Program: Ratings Peers (spatial lag)",
                              "Mean Currency Crisis: Geographic Peers (spatial lag)",
                              "Mean Currency Crisis: MSCI Peers (spatial lag)",
                              "Mean Currency Crisis: Ratings Peers (spatial lag)",
                              "Mean Banking Crisis: Geographic Peers (spatial lag)",
                              "Mean Banking Crisis: MSCI Peers (spatial lag)",
                              "Mean Banking Crisis: Ratings Peers (spatial lag)",
                              
                              "Log Volatility (ARIMA, lag) x Geographic Peers (low KAI)",
                              "Log Volatility (ARIMA, lag) x Geographic Peers (medium KAI)",
                              "Log Volatility (ARIMA, lag) x Geographic Peers (high KAI)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (low KAI)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (medium KAI)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (high KAI)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (low KAI)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (medium KAI)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (high KAI)",
                              
                              "Log Volatility (ARIMA, lag) x Geographic Peers (low KAO)",
                              "Log Volatility (ARIMA, lag) x Geographic Peers (medium KAO)",
                              "Log Volatility (ARIMA, lag) x Geographic Peers (high KAO)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (low KAO)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (medium KAO)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (high KAO)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (low KAO)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (medium KAO)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (high KAO)",
                              "Log Volatility (ARIMA, lag) x Partisanship Peers (low KAO)",
                              "Log Volatility (ARIMA, lag) x Partisanship Peers (medium KAO)",
                              "Log Volatility (ARIMA, lag) x Partisanship Peers (high KAO)",
                              
                              "Log Volatility (ARIMA, lag) x Geographic Peers (low KAO short)",
                              "Log Volatility (ARIMA, lag) x Geographic Peers (medium KAO short)",
                              "Log Volatility (ARIMA, lag) x Geographic Peers (high KAO short)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (low KAO short)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (medium KAO short)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (high KAO short)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (low KAO short)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (medium KAO short)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (high KAO short)",
                              
                              "Log Volatility (ARIMA, lag) x Federal Funds Rate (high)",
                              "Federal Funds Rate (high) x Geographic Peers (medium KAO)",
                              "Federal Funds Rate (high) x Geographic Peers (high KAO)",
                              "Federal Funds Rate (high) x MSCI Peers (medium KAO)",
                              "Federal Funds Rate (high) x MSCI Peers (high KAO)",
                              "Federal Funds Rate (high) x Ratings Peers (medium KAO)",
                              "Federal Funds Rate (high) x Ratings Peers (high KAO)",
                              
                              "Log Volatility (ARIMA, lag) x VIX Index (high)",
                              "VIX Index (high) x Geographic Peers (medium KAO)",
                              "VIX Index (high) x Geographic Peers (high KAO)",
                              "VIX Index (high) x MSCI Peers (medium KAO)",
                              "VIX Index (high) x MSCI Peers (high KAO)",
                              "VIX Index (high) x Ratings Peers (medium KAO)",
                              "VIX Index (high) x Ratings Peers (high KAO)",
                              
                              "Log Volatility (ARIMA, lag) x Global (low KAO, lag)",
                              "Log Volatility (ARIMA, lag) x Global (medium KAO, lag)",
                              "Log Volatility (ARIMA, lag) x Top Growth Countries (low KAO, lag)",
                              "Log Volatility (ARIMA, lag) x Top Growth Countries (medium KAO, lag)",
                              
                              "Log Volatility (ARIMA, lag) x Geographic Peers (medium KAO) x Federal Funds Rate (high)",
                              "Log Volatility (ARIMA, lag) x Geographic Peers (high KAO) x Federal Funds Rate (high)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (medium KAO) x Federal Funds Rate (high)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (high KAO) x Federal Funds Rate (high)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (medium KAO) x Federal Funds Rate (high)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (high KAO) x Federal Funds Rate (high)",
                              
                              "Log Volatility (ARIMA, lag) x Geographic Peers (medium KAO) x VIX (high)",
                              "Log Volatility (ARIMA, lag) x Geographic Peers (high KAO) x VIX (high)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (medium KAO) x VIX (high)",
                              "Log Volatility (ARIMA, lag) x MSCI Peers (high KAO) x VIX (high)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (medium KAO) x VIX (high)",
                              "Log Volatility (ARIMA, lag) x Ratings Peers (high KAO) x VIX (high)",
                              
                              "Real Interest Rate (\\%, lag)",
                              "Inflation (annual \\%, lag)",
                              "Total Reserves (months of imports, lag)",
                              "Trade (\\% of GDP, log, lag)",
                              "Currency Crisis (dummy, lag)",
                              "IMF Loan Program (dummy, lag)",
                              "Banking Crisis (dummy, lag)",
                              "Log Constant GDP (2010 USDB, lag)",
                              "Log Constant GDP per capita (2010 USD, lag)",
                              "Exchange Rate Peg (dummy, lag)",
                              "Democracy (polity2, lag)",
                              "BIT with USA (dummy)",
                              "Net Portfolio Investment (billion USD, lag)",
                              "Post-Communist Country (dummy)",
                              "Right/Center Government (dummy, lag)",
                              "Veto Players (lag)")
                 )

# function to replace variable names
replaceVarName <- function(var.vec, var.df){
  # Prepare output vector
  out.vec <- rep(NA, length(var.vec))
  matches <- match(var.vec, var.df$var)
  out.vec <- var.df[matches,]$var_name
  
  if(any(is.na(out.vec))){
    warning(paste("Variable concordence missing: ", 
                  paste(var.vec[is.na(out.vec)], collapse = ", "), 
                  sep = ""))
  } else{
    #print("All variables successfully converted")
  }
  
  return(out.vec)
}


################################################################################
## Table B.1
## Linear Mixed Effects Regression Results
################################################################################
## KAI
# column (1): BASE
lme.kai.arima.b <- lmer(kai ~ 
                          ln_ave_arimanpf_lag + 
                          log(gdp_const_lag) + 
                          log(gdp_pc_const_lag) + 
                          log(trade_open_lag) + 
                          inflation_lag + 
                          real_interest_rate_lag + 
                          peg_lag + 
                          polity2_lag + 
                          checks_lag +
                          (1 | year) + (1 | iso3n), 
                        data = data.merge)
summary(lme.kai.arima.b) 

# column (2): GEO
lme.kai.arima.geo.high <- lmer(kai ~ 
                                 ln_ave_arimanpf_lag * geodist_kai_tercile_low + 
                                 ln_ave_arimanpf_lag * geodist_kai_tercile_med + 
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) + 
                                 log(trade_open_lag) + 
                                 inflation_lag + 
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag +
                                 checks_lag + 
                                 (1 | year) + (1 | iso3n), 
                               data = data.merge)
summary(lme.kai.arima.geo.high)

# column (3): MSCI
lme.kai.arima.mar.high <- lmer(kai ~ 
                                 ln_ave_arimanpf_lag * msci_kai_tercile_low + 
                                 ln_ave_arimanpf_lag * msci_kai_tercile_med + 
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) + 
                                 log(trade_open_lag) + 
                                 inflation_lag +
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag +
                                 checks_lag + 
                                 (1 | year) + (1 | iso3n),
                               data = data.merge)
summary(lme.kai.arima.mar.high)

# column (4): RATINGS
lme.kai.arima.fitch.high <- lmer(kai ~ 
                                   ln_ave_arimanpf_lag * fitch_kai_tercile_low + 
                                   ln_ave_arimanpf_lag * fitch_kai_tercile_med + 
                                   log(gdp_const_lag) + 
                                   log(gdp_pc_const_lag) + 
                                   log(trade_open_lag) + 
                                   inflation_lag + 
                                   real_interest_rate_lag + 
                                   peg_lag + 
                                   polity2_lag +
                                   checks_lag + 
                                   (1 | year) + (1 | iso3n),
                                 data = data.merge)
summary(lme.kai.arima.fitch.high)

## KAO
# column (5): BASE
lme.kao.arima.b <- lmer(kao ~ 
                          ln_ave_arimanpf_lag + 
                          log(gdp_const_lag) + 
                          log(gdp_pc_const_lag) + 
                          log(trade_open_lag) + 
                          inflation_lag + 
                          real_interest_rate_lag + 
                          peg_lag + 
                          polity2_lag + 
                          checks_lag +
                          (1 | year) + (1 | iso3n),
                        data = data.merge)
summary(lme.kao.arima.b) 

# column (6): GEO
lme.kao.arima.geo.high <- lmer(kao ~ 
                                 ln_ave_arimanpf_lag * geodist_kao_tercile_low +
                                 ln_ave_arimanpf_lag * geodist_kao_tercile_med +
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) +
                                 log(trade_open_lag) + 
                                 inflation_lag +
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag + 
                                 checks_lag + 
                                 (1 | year) + (1 | iso3n),
                               data = data.merge)
summary(lme.kao.arima.geo.high)

# column (7): MSCI
lme.kao.arima.mar.high <- lmer(kao ~ 
                                 ln_ave_arimanpf_lag * msci_kao_tercile_low + 
                                 ln_ave_arimanpf_lag * msci_kao_tercile_med + 
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) + 
                                 log(trade_open_lag) + 
                                 inflation_lag + 
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag + 
                                 checks_lag + 
                                 (1 | year) + (1 | iso3n),
                               data = data.merge)
summary(lme.kao.arima.mar.high)

# column (8): RATINGS
lme.kao.arima.fitch.high <- lmer(kao ~ 
                                   ln_ave_arimanpf_lag * fitch_kao_tercile_low + 
                                   ln_ave_arimanpf_lag * fitch_kao_tercile_med + 
                                   log(gdp_const_lag) + 
                                   log(gdp_pc_const_lag) + 
                                   log(trade_open_lag) + 
                                   inflation_lag + 
                                   real_interest_rate_lag + 
                                   peg_lag + 
                                   polity2_lag + 
                                   checks_lag +
                                   (1 | year) + (1 | iso3n),
                                 data = data.merge)
summary(lme.kao.arima.fitch.high)

## produce table
# set models
main.out <- list(lme.kai.arima.b, 
                 lme.kai.arima.geo.high, 
                 lme.kai.arima.mar.high, 
                 lme.kai.arima.fitch.high,
                 
                 lme.kao.arima.b, 
                 lme.kao.arima.geo.high, 
                 lme.kao.arima.mar.high, 
                 lme.kao.arima.fitch.high)

# set model names
mod.names.m <- c("KAI-BASE", "KAI-GEO", "KAI-MSCI", "KAI-RATINGS",
                 "KAO-BASE", "KAO-GEO", "KAO-MSCI", "KAO-RATINGS")

# set var order
var.order.m <- c(1:13, 
                 22:33,
                 14:21)

var.label.m <- c("ln_ave_arimanpf_lag",
                 "geodist_kai_tercile_low",
                 "geodist_kai_tercile_med",
                 "msci_kai_tercile_low",
                 "msci_kai_tercile_med",
                 "fitch_kai_tercile_low",
                 "fitch_kai_tercile_med",
                 "geodist_kao_tercile_low",
                 "geodist_kao_tercile_med",
                 "msci_kao_tercile_low",
                 "msci_kao_tercile_med",
                 "fitch_kao_tercile_low",
                 "fitch_kao_tercile_med",
                 
                 "ln_ave_arimanpf_lag:geodist_kai_tercile_low",
                 "ln_ave_arimanpf_lag:geodist_kai_tercile_med",
                 "ln_ave_arimanpf_lag:msci_kai_tercile_low",
                 "ln_ave_arimanpf_lag:msci_kai_tercile_med",
                 "ln_ave_arimanpf_lag:fitch_kai_tercile_low",
                 "ln_ave_arimanpf_lag:fitch_kai_tercile_med",
                 
                 "ln_ave_arimanpf_lag:geodist_kao_tercile_low",
                 "ln_ave_arimanpf_lag:geodist_kao_tercile_med",
                 "ln_ave_arimanpf_lag:msci_kao_tercile_low",
                 "ln_ave_arimanpf_lag:msci_kao_tercile_med",
                 "ln_ave_arimanpf_lag:fitch_kao_tercile_low",
                 "ln_ave_arimanpf_lag:fitch_kao_tercile_med",
                 
                 "log(gdp_const_lag)",
                 "log(gdp_pc_const_lag)",
                 "log(trade_open_lag)",
                 "inflation_lag",
                 "real_interest_rate_lag",
                 "peg_lag",
                 "polity2_lag",
                 "checks_lag")

# save
#sink(file.path(MAIN_DIR, "Table-B.1.tex"))
sink(file.path(MAIN_DIR, "Table-B.1.txt"))
stargazer(main.out,
          #type = "latex",
          type = "text",
          title = "Linear Mixed Effects Regression Results",
          dep.var.labels = "",
          dep.var.labels.include = FALSE,
          column.labels = mod.names.m,
          order = var.order.m,
          covariate.labels = replaceVarName(var.vec = var.label.m,
                                            var.df = var.df),
          add.lines = list(c("Varying Intercept: Country",
                             rep("Yes", 8)),
                           c("Varying Intercept: Year",
                             rep("Yes", 8)),
                           c("Number of Countries", 
                             formatC(n_distinct(lme.kai.arima.b@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kai.arima.geo.high@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kai.arima.mar.high@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kai.arima.fitch.high@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.b@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.geo.high@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.high@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.high@frame$iso3n), big.mark = ",")
                           ),          
                           c("Number of Years", 
                             formatC(n_distinct(lme.kai.arima.b@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kai.arima.geo.high@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kai.arima.mar.high@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kai.arima.fitch.high@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.b@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.geo.high@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.high@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.high@frame$year), big.mark = ",")
                           )
          ),
          label = "tb:lme-main",
          single.row = FALSE,
          column.sep.width = "0.01pt",
          no.space = TRUE,
          df = FALSE,
          font.size = "tiny",
          star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
          star.char = c("+", "*", "**", "***"),
          notes = c("In the interaction models, the first row presents results for which peers’ capital inflow/outflow restrictions are high. Standard errors in parentheses. $^{+}$p$<$0.1; $^{*}$p$<$0.05; $^{**}$p$<$0.01; $^{***}$p$<$0.001"), 
          notes.append = FALSE)
sink()


################################################################################
## Table B.2
## Fixed Effects Regression Results
################################################################################
## GEO
# column (1)
felm.kao.arima.geo.f.c <- felm(kao ~ 
                                 ln_ave_arimanpf_lag * geodist_kao_tercile_low + 
                                 ln_ave_arimanpf_lag * geodist_kao_tercile_med + 
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) + 
                                 log(trade_open_lag) + 
                                 inflation_lag + 
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag + 
                                 checks_lag 
                               | iso3n | 0 | iso3n, 
                               data = data.merge,
                               keepX = TRUE)
summary(felm.kao.arima.geo.f.c)

# column (2)
felm.kao.arima.geo.f.cy <- felm(kao ~ 
                                  ln_ave_arimanpf_lag * geodist_kao_tercile_low + 
                                  ln_ave_arimanpf_lag * geodist_kao_tercile_med + 
                                  log(gdp_const_lag) + 
                                  log(gdp_pc_const_lag) + 
                                  log(trade_open_lag) + 
                                  inflation_lag + 
                                  real_interest_rate_lag + 
                                  peg_lag + 
                                  polity2_lag +
                                  checks_lag
                                | iso3n + year| 0 | iso3n, 
                                data = data.merge,
                                keepX = TRUE)
summary(felm.kao.arima.geo.f.cy)

## MSCI
# column (3)
felm.kao.arima.msci.f.c <- felm(kao ~ 
                                  ln_ave_arimanpf_lag * msci_kao_tercile_low + 
                                  ln_ave_arimanpf_lag * msci_kao_tercile_med + 
                                  log(gdp_const_lag) + 
                                  log(gdp_pc_const_lag) + 
                                  log(trade_open_lag) + 
                                  inflation_lag + 
                                  real_interest_rate_lag + 
                                  peg_lag + 
                                  polity2_lag + 
                                  checks_lag
                                | iso3n | 0 | iso3n, 
                                data = data.merge,
                                keepX = TRUE)
summary(felm.kao.arima.msci.f.c)

# column (4)
felm.kao.arima.msci.f.cy <- felm(kao ~ 
                                   ln_ave_arimanpf_lag * msci_kao_tercile_low + 
                                   ln_ave_arimanpf_lag * msci_kao_tercile_med + 
                                   log(gdp_const_lag) + 
                                   log(gdp_pc_const_lag) + 
                                   log(trade_open_lag) + 
                                   inflation_lag + 
                                   real_interest_rate_lag + 
                                   peg_lag + 
                                   polity2_lag +
                                   checks_lag 
                                 | iso3n + year | 0 | iso3n, 
                                 data = data.merge,
                                 keepX = TRUE)
summary(felm.kao.arima.msci.f.cy)

## RATINGS
# column (5)
felm.kao.arima.fitch.f.c <- felm(kao ~ 
                                   ln_ave_arimanpf_lag * fitch_kao_tercile_low + 
                                   ln_ave_arimanpf_lag * fitch_kao_tercile_med + 
                                   log(gdp_const_lag) + 
                                   log(gdp_pc_const_lag) + 
                                   log(trade_open_lag) + 
                                   inflation_lag + 
                                   real_interest_rate_lag + 
                                   peg_lag + 
                                   polity2_lag + 
                                   checks_lag 
                                 | iso3n | 0 | iso3n, 
                                 data = data.merge,
                                 keepX = TRUE)
summary(felm.kao.arima.fitch.f.c)

# column (6)
felm.kao.arima.fitch.f.cy <- felm(kao ~ 
                                    ln_ave_arimanpf_lag * fitch_kao_tercile_low + 
                                    ln_ave_arimanpf_lag * fitch_kao_tercile_med + 
                                    log(gdp_const_lag) + 
                                    log(gdp_pc_const_lag) + 
                                    log(trade_open_lag) + 
                                    inflation_lag + 
                                    real_interest_rate_lag + 
                                    peg_lag + 
                                    polity2_lag +
                                    checks_lag
                                  | iso3n + year| 0 | iso3n, 
                                  data = data.merge,
                                  keepX = TRUE)
summary(felm.kao.arima.fitch.f.cy)

## produce tables
# set models
felm.out <- list(felm.kao.arima.geo.f.c,
                 felm.kao.arima.geo.f.cy,
                 felm.kao.arima.msci.f.c,
                 felm.kao.arima.msci.f.cy,
                 felm.kao.arima.fitch.f.c,
                 felm.kao.arima.fitch.f.cy)

# set model names
mod.names.felm <- c("KAO-GEO", "KAO-GEO", 
                    "KAO-MSCI", "KAO-MSCI", 
                    "KAO-RATINGS", "KAO-RATINGS")

# set var order
var.order.felm <- c(1:7, 
                    16:21,
                    8:15)

# set var labels
var.label.felm <- c("ln_ave_arimanpf_lag",
                    "geodist_kao_tercile_low",
                    "geodist_kao_tercile_med",
                    "msci_kao_tercile_low",
                    "msci_kao_tercile_med",
                    "fitch_kao_tercile_low",
                    "fitch_kao_tercile_med",
                    
                    "ln_ave_arimanpf_lag:geodist_kao_tercile_low",
                    "ln_ave_arimanpf_lag:geodist_kao_tercile_med",
                    "ln_ave_arimanpf_lag:msci_kao_tercile_low",
                    "ln_ave_arimanpf_lag:msci_kao_tercile_med",
                    "ln_ave_arimanpf_lag:fitch_kao_tercile_low",
                    "ln_ave_arimanpf_lag:fitch_kao_tercile_med",
                    
                    "log(gdp_const_lag)",
                    "log(gdp_pc_const_lag)",
                    "log(trade_open_lag)",
                    "inflation_lag",
                    "real_interest_rate_lag",
                    "peg_lag",
                    "polity2_lag",
                    "checks_lag")

# save
#sink(file.path(MAIN_DIR, "Table-B.2.tex"))
sink(file.path(MAIN_DIR, "Table-B.2.txt"))
stargazer(felm.out,
          #type = "latex",
          type = "text",
          title = "Fixed Effects Regression Results",
          dep.var.labels = "",
          dep.var.labels.include = FALSE,
          column.labels = mod.names.felm,
          order = var.order.felm,
          covariate.labels = replaceVarName(var.vec = var.label.felm,
                                            var.df = var.df),
          add.lines = list(c("Country Fixed-Effects",
                             rep("Yes", 6)),
                           c("Year Fixed-Effects",
                             c("", "Yes", "", "Yes", "", "Yes")),
                           c("Number of Countries", 
                             formatC(n_distinct(felm.kao.arima.geo.f.c$clustervar$iso3n), big.mark = ","),
                             formatC(n_distinct(felm.kao.arima.geo.f.cy$clustervar$iso3n), big.mark = ","),
                             formatC(n_distinct(felm.kao.arima.msci.f.c$clustervar$iso3n), big.mark = ","),
                             formatC(n_distinct(felm.kao.arima.msci.f.cy$clustervar$iso3n), big.mark = ","),
                             formatC(n_distinct(felm.kao.arima.fitch.f.c$clustervar$iso3n), big.mark = ","),
                             formatC(n_distinct(felm.kao.arima.fitch.f.cy$clustervar$iso3n), big.mark = ",")
                           ),          
                           c("Number of Years", 
                             formatC(n_distinct(data.merge[-as.vector(felm.kao.arima.geo.f.c$na.action),]$year), big.mark = ","),
                             formatC(n_distinct(data.merge[-as.vector(felm.kao.arima.geo.f.cy$na.action),]$year), big.mark = ","),
                             formatC(n_distinct(data.merge[-as.vector(felm.kao.arima.msci.f.c$na.action),]$year), big.mark = ","),
                             formatC(n_distinct(data.merge[-as.vector(felm.kao.arima.msci.f.cy$na.action),]$year), big.mark = ","),
                             formatC(n_distinct(data.merge[-as.vector(felm.kao.arima.fitch.f.c$na.action),]$year), big.mark = ","),
                             formatC(n_distinct(data.merge[-as.vector(felm.kao.arima.fitch.f.cy$na.action),]$year), big.mark = ",")
                           )
          ),
          label = "tb:felm",
          single.row = FALSE,
          column.sep.width = "0.01pt",
          no.space = TRUE,
          df = FALSE,
          font.size = "tiny",
          star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
          star.char = c("+", "*", "**", "***"),
          notes = c("The first row presents results for which peers' capital outflow restrictions are high. Standard errors clustered by country in parentheses. $^{+}$p$<$0.1; $^{*}$p$<$0.05; $^{**}$p$<$0.01; $^{***}$p$<$0.001"), 
          notes.append = FALSE)
sink()


################################################################################
## Table B.3
## Linear Mixed Effects Regression Results: Short-Term Outflow Restrictions
################################################################################
# column (1): BASE 
lme.kao.short.arima.b <- lmer(kao_short ~ 
                                ln_ave_arimanpf_lag +
                                log(gdp_const_lag) + 
                                log(gdp_pc_const_lag) + 
                                log(trade_open_lag) +
                                inflation_lag + 
                                real_interest_rate_lag + 
                                peg_lag + 
                                polity2_lag + 
                                checks_lag +
                                (1 | year) + (1 | iso3n),
                              data = data.merge,
                              control = lmerControl(optCtrl = list(maxfun = 2e10)))
summary(lme.kao.short.arima.b)

# column (2): GEO
lme.kao.short.arima.geo <- lmer(kao_short ~ 
                                  ln_ave_arimanpf_lag * geodist_kao_short_tercile_med +
                                  ln_ave_arimanpf_lag * geodist_kao_short_tercile_low +
                                  log(gdp_const_lag) + 
                                  log(gdp_pc_const_lag) + 
                                  log(trade_open_lag) +
                                  inflation_lag + 
                                  real_interest_rate_lag + 
                                  peg_lag + 
                                  polity2_lag + 
                                  checks_lag +
                                  (1 | year) + (1 | iso3n),
                                data = data.merge)
summary(lme.kao.short.arima.geo) 

# column (3): MSCI
lme.kao.short.arima.mar <- lmer(kao_short ~ 
                                  ln_ave_arimanpf_lag * msci_kao_short_tercile_med +
                                  ln_ave_arimanpf_lag * msci_kao_short_tercile_low +
                                  log(gdp_const_lag) + 
                                  log(gdp_pc_const_lag) + 
                                  log(trade_open_lag) +
                                  inflation_lag + 
                                  real_interest_rate_lag +
                                  peg_lag + 
                                  polity2_lag + 
                                  checks_lag +
                                  (1 | year) + (1 | iso3n), 
                                data = data.merge)
summary(lme.kao.short.arima.mar)

# column (4): RATINGS
lme.kao.short.arima.fitch <- lmer(kao_short ~ 
                                    ln_ave_arimanpf_lag * fitch_kao_short_tercile_med +
                                    ln_ave_arimanpf_lag * fitch_kao_short_tercile_low +
                                    log(gdp_const_lag) + 
                                    log(gdp_pc_const_lag) + 
                                    log(trade_open_lag) +
                                    inflation_lag + 
                                    real_interest_rate_lag + 
                                    peg_lag + 
                                    polity2_lag + 
                                    checks_lag +
                                    (1 | year) + (1 | iso3n), 
                                  data = data.merge)
summary(lme.kao.short.arima.fitch) 

## produce tables
# set models
short.out <- list(lme.kao.short.arima.b, 
                  lme.kao.short.arima.geo, 
                  lme.kao.short.arima.mar, 
                  lme.kao.short.arima.fitch)

# set model names
mod.names.short <- c("BASE", "GEO", "MSCI", "RATINGS")

# set var labels
var.label.short <- c("ln_ave_arimanpf_lag",
                     
                     "geodist_kao_short_tercile_low",
                     "geodist_kao_short_tercile_med",
                     "msci_kao_short_tercile_low",
                     "msci_kao_short_tercile_med",
                     "fitch_kao_short_tercile_low",
                     "fitch_kao_short_tercile_med",
                     
                     "ln_ave_arimanpf_lag:geodist_kao_short_tercile_low",
                     "ln_ave_arimanpf_lag:geodist_kao_short_tercile_med",
                     "ln_ave_arimanpf_lag:msci_kao_short_tercile_low",
                     "ln_ave_arimanpf_lag:msci_kao_short_tercile_med",
                     "ln_ave_arimanpf_lag:fitch_kao_short_tercile_low",
                     "ln_ave_arimanpf_lag:fitch_kao_short_tercile_med",
                     
                     "log(gdp_const_lag)",
                     "log(gdp_pc_const_lag)",
                     "log(trade_open_lag)",
                     "inflation_lag",
                     "real_interest_rate_lag",
                     "peg_lag",
                     "polity2_lag",
                     "checks_lag")

# set var order
var.order.short <- c(1, 
                     3, 2,
                     5, 4,
                     7, 6,
                     17, 16,
                     19, 18,
                     21, 20,
                     8:15)

#sink(file.path(MAIN_DIR, "Table-B.3.tex"))
sink(file.path(MAIN_DIR, "Table-B.3.txt"))
stargazer(short.out,
          #type = "latex",
          type = "text",
          title = "Linear Mixed Effects Regression Results: Short-Term Outflow Restrictions",
          dep.var.labels = "Outflow Restrictions on Short-Term Capital Only (KAO short)",
          dep.var.labels.include = TRUE,
          column.labels = mod.names.short,
          order = var.order.short,
          covariate.labels = replaceVarName(var.vec = var.label.short,
                                            var.df = var.df),
          add.lines = list(c("Varying Intercept: Country",
                             rep("Yes", 4)),
                           c("Varying Intercept: Year",
                             rep("Yes", 4)),
                           c("Number of Countries", 
                             formatC(n_distinct(lme.kao.short.arima.b@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.short.arima.geo@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.short.arima.mar@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.short.arima.fitch@frame$iso3n), big.mark = ",")),          
                           c("Number of Years", 
                             formatC(n_distinct(lme.kao.short.arima.b@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.short.arima.geo@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.short.arima.mar@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.short.arima.fitch@frame$year), big.mark = ","))
          ),
          label = "tb:lme-short",
          single.row = FALSE,
          column.sep.width = "0.01pt",
          no.space = TRUE,
          df = FALSE,
          font.size = "tiny",
          star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
          star.char = c("+", "*", "**", "***"),
          notes = c("In the interaction models, the first row presents results for which peers’ capital outflow restrictions are high. Standard errors in parentheses. $^{+}$p$<$0.1; $^{*}$p$<$0.05; $^{**}$p$<$0.01; $^{***}$p$<$0.001"), 
          notes.align = "l",
          notes.append = FALSE)
sink()


################################################################################
## Table B.4
## Linear Mixed Effects Regression Results: Controlling for Peer Economic Crises
################################################################################
## Currency Crisis 
# column (1): GEO
lme.kao.arima.geo.crisis2 <- lmer(kao ~ 
                                    ln_ave_arimanpf_lag * geodist_kao_tercile_low + 
                                    ln_ave_arimanpf_lag * geodist_kao_tercile_med + 
                                    log(gdp_const_lag) + 
                                    log(gdp_pc_const_lag) + 
                                    log(trade_open_lag) + 
                                    inflation_lag + 
                                    real_interest_rate_lag + 
                                    peg_lag + 
                                    polity2_lag +
                                    sl_geodist_crisis2 + 
                                    crisis2_lag + 
                                    checks_lag +
                                    (1 | year) + (1 | iso3n),
                                  data = data.merge)
summary(lme.kao.arima.geo.crisis2) 

# column (2): MSCI
lme.kao.arima.mar.crisis2 <- lmer(kao ~ 
                                    ln_ave_arimanpf_lag * msci_kao_tercile_low + 
                                    ln_ave_arimanpf_lag * msci_kao_tercile_med + 
                                    log(gdp_const_lag) + 
                                    log(gdp_pc_const_lag) + 
                                    log(trade_open_lag) + 
                                    inflation_lag + 
                                    real_interest_rate_lag + 
                                    peg_lag + 
                                    polity2_lag + 
                                    msci_mean_crisis2_lag +
                                    crisis2_lag + 
                                    checks_lag +
                                    (1 | year) + (1 | iso3n), 
                                  data = data.merge)
summary(lme.kao.arima.mar.crisis2)

# column (3): RATINGS
lme.kao.arima.fitch.crisis2 <- lmer(kao ~ 
                                      ln_ave_arimanpf_lag * fitch_kao_tercile_low + 
                                      ln_ave_arimanpf_lag * fitch_kao_tercile_med + 
                                      log(gdp_const_lag) + 
                                      log(gdp_pc_const_lag) + 
                                      log(trade_open_lag) +
                                      inflation_lag + 
                                      real_interest_rate_lag + 
                                      peg_lag + 
                                      polity2_lag + 
                                      sl_fitch_crisis2 +
                                      crisis2_lag + 
                                      checks_lag +
                                      (1 | year) + (1 | iso3n),
                                    data = data.merge)
summary(lme.kao.arima.fitch.crisis2) 

## IMF Program
# column (4): GEO
lme.kao.arima.geo.imf <- lmer(kao ~ 
                                ln_ave_arimanpf_lag * geodist_kao_tercile_low + 
                                ln_ave_arimanpf_lag * geodist_kao_tercile_med + 
                                log(gdp_const_lag) + 
                                log(gdp_pc_const_lag) + 
                                log(trade_open_lag) + 
                                inflation_lag + 
                                real_interest_rate_lag + 
                                peg_lag + 
                                polity2_lag +
                                sl_geodist_imf + 
                                imf_program_lag +
                                checks_lag +
                                (1 | year) + (1 | iso3n),
                              data = data.merge)
summary(lme.kao.arima.geo.imf) 

# column (5): MSCI
lme.kao.arima.mar.imf <- lmer(kao ~ 
                                ln_ave_arimanpf_lag * msci_kao_tercile_low + 
                                ln_ave_arimanpf_lag * msci_kao_tercile_med + 
                                log(gdp_const_lag) + 
                                log(gdp_pc_const_lag) + 
                                log(trade_open_lag) + 
                                inflation_lag + 
                                real_interest_rate_lag + 
                                peg_lag + 
                                polity2_lag + 
                                msci_mean_imf_lag +
                                imf_program_lag + 
                                checks_lag +
                                (1 | year) + (1 | iso3n), 
                              data = data.merge)
summary(lme.kao.arima.mar.imf)

# column (6): RATINGS
lme.kao.arima.fitch.imf <- lmer(kao ~ 
                                  ln_ave_arimanpf_lag * fitch_kao_tercile_low + 
                                  ln_ave_arimanpf_lag * fitch_kao_tercile_med + 
                                  log(gdp_const_lag) + 
                                  log(gdp_pc_const_lag) + 
                                  log(trade_open_lag) + 
                                  inflation_lag + 
                                  real_interest_rate_lag + 
                                  peg_lag + 
                                  polity2_lag + 
                                  sl_fitch_imf +
                                  imf_program_lag + 
                                  checks_lag +
                                  (1 | year) + (1 | iso3n),
                                data = data.merge)
summary(lme.kao.arima.fitch.imf)

## Banking Crisis
# column (7): GEO
lme.kao.arima.geo.bank.crisis <- lmer(kao ~ 
                                        ln_ave_arimanpf_lag * geodist_kao_tercile_low + 
                                        ln_ave_arimanpf_lag * geodist_kao_tercile_med + 
                                        log(gdp_const_lag) + 
                                        log(gdp_pc_const_lag) + 
                                        log(trade_open_lag) + 
                                        inflation_lag + 
                                        real_interest_rate_lag + 
                                        peg_lag + 
                                        polity2_lag +
                                        sl_geodist_bank_crisis + 
                                        bank_crisis_lag + 
                                        checks_lag +
                                        (1 | year) + (1 | iso3n),
                                      data = data.merge)
summary(lme.kao.arima.geo.bank.crisis) 

# column (8): MSCI
lme.kao.arima.mar.bank.crisis <- lmer(kao ~ 
                                        ln_ave_arimanpf_lag * msci_kao_tercile_low + 
                                        ln_ave_arimanpf_lag * msci_kao_tercile_med + 
                                        log(gdp_const_lag) + 
                                        log(gdp_pc_const_lag) + 
                                        log(trade_open_lag) + 
                                        inflation_lag + 
                                        real_interest_rate_lag + 
                                        peg_lag + 
                                        polity2_lag + 
                                        msci_mean_bank_crisis_lag +
                                        bank_crisis_lag + 
                                        checks_lag +
                                        (1 | year) + (1 | iso3n), 
                                      data = data.merge)
summary(lme.kao.arima.mar.bank.crisis)

# column (9): RATINGS
lme.kao.arima.fitch.bank.crisis <- lmer(kao ~ 
                                          ln_ave_arimanpf_lag * fitch_kao_tercile_low + 
                                          ln_ave_arimanpf_lag * fitch_kao_tercile_med + 
                                          log(gdp_const_lag) + 
                                          log(gdp_pc_const_lag) + 
                                          log(trade_open_lag) + 
                                          inflation_lag + 
                                          real_interest_rate_lag + 
                                          peg_lag + 
                                          polity2_lag + 
                                          sl_fitch_bank_crisis +
                                          bank_crisis_lag + 
                                          checks_lag +
                                          (1 | year) + (1 | iso3n),
                                        data = data.merge)
summary(lme.kao.arima.fitch.bank.crisis) 

## produce tables
# set models
crisis.out <- list(lme.kao.arima.geo.crisis2, 
                   lme.kao.arima.mar.crisis2, 
                   lme.kao.arima.fitch.crisis2,
                   lme.kao.arima.geo.imf, 
                   lme.kao.arima.mar.imf, 
                   lme.kao.arima.fitch.imf,
                   lme.kao.arima.geo.bank.crisis, 
                   lme.kao.arima.mar.bank.crisis, 
                   lme.kao.arima.fitch.bank.crisis
                   )

# set model names
mod.names.crisis <- c("GEO: Crisis", 
                      "MSCI: Crisis", 
                      "RATINGS: Crisis",
                      
                      "GEO: IMF", 
                      "MSCI: IMF", 
                      "RATINGS: IMF",
                      
                      "GEO: Bank", 
                      "MSCI: Bank", 
                      "RATINGS: Bank"
                      )

# set var labels
var.label.crisis <- c("ln_ave_arimanpf_lag",
                      
                      "geodist_kao_tercile_low",
                      "geodist_kao_tercile_med",
                      "msci_kao_tercile_low",
                      "msci_kao_tercile_med",
                      "fitch_kao_tercile_low",
                      "fitch_kao_tercile_med",
                      
                      "ln_ave_arimanpf_lag:geodist_kao_tercile_low",
                      "ln_ave_arimanpf_lag:geodist_kao_tercile_med",
                      "ln_ave_arimanpf_lag:msci_kao_tercile_low",
                      "ln_ave_arimanpf_lag:msci_kao_tercile_med",
                      "ln_ave_arimanpf_lag:fitch_kao_tercile_low",
                      "ln_ave_arimanpf_lag:fitch_kao_tercile_med",
                      
                      "log(gdp_const_lag)",
                      "log(gdp_pc_const_lag)",
                      "log(trade_open_lag)",
                      "inflation_lag",
                      "real_interest_rate_lag",
                      "peg_lag",
                      "polity2_lag",
                      "checks_lag",
                      
                      "sl_geodist_crisis2",
                      "msci_mean_crisis2_lag",
                      "sl_fitch_crisis2",
                      "crisis2_lag",
                      
                      "sl_geodist_imf",
                      "msci_mean_imf_lag",
                      "sl_fitch_imf",
                      "imf_program_lag",
                      
                      "sl_geodist_bank_crisis",
                      "msci_mean_bank_crisis_lag",
                      "sl_fitch_bank_crisis",
                      "bank_crisis_lag"
                      )

# set var order
var.order.crisis <- c(1:7,
                      28:33,
                      8:14, 27,
                      15:26)

#sink(file.path(MAIN_DIR, "Table-B.4.tex"))
sink(file.path(MAIN_DIR, "Table-B.4.txt"))
stargazer(crisis.out,
          #type = "latex",
          type = "text",
          title = "Linear Mixed Effects Regression Results: Controlling for Peer Economic Crises",
          dep.var.labels = "Outflow Restrictions (KAO)",
          dep.var.labels.include = TRUE,
          column.labels = mod.names.crisis,
          order = var.order.crisis,
          covariate.labels = replaceVarName(var.vec = var.label.crisis,
                                            var.df = var.df),
          add.lines = list(c("Varying Intercept: Country",
                             rep("Yes", 9)),
                           c("Varying Intercept: Year",
                             rep("Yes", 9)),
                           c("Number of Countries", 
                             formatC(n_distinct(lme.kao.arima.geo.crisis2@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.crisis2@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.crisis2@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.geo.imf@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.imf@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.imf@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.geo.bank.crisis@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.bank.crisis@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.bank.crisis@frame$iso3n), big.mark = ",")
                           ),          
                           c("Number of Years", 
                             formatC(n_distinct(lme.kao.arima.geo.crisis2@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.crisis2@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.crisis2@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.geo.imf@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.imf@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.imf@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.geo.bank.crisis@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.bank.crisis@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.bank.crisis@frame$year), big.mark = ",")
                           )),
          label = "tb:lme-crisis",
          single.row = FALSE,
          column.sep.width = "0.01pt",
          no.space = TRUE,
          df = FALSE,
          font.size = "tiny",
          star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
          star.char = c("+", "*", "**", "***"),
          notes = c("The first row presents results for which peers’ capital outflow restrictions are high. Standard errors in parentheses. $^{+}$p$<$0.1; $^{*}$p$<$0.05; $^{**}$p$<$0.01; $^{***}$p$<$0.001"), 
          notes.align = "l",
          notes.append = FALSE)
sink()


################################################################################
## Table B.5
## Linear Mixed Effects Regression Results: Accounting for Partisanship
################################################################################
# column (1): GEO
lme.kao.arima.geo.exec <- lmer(kao ~ 
                                 ln_ave_arimanpf_lag * geodist_kao_tercile_low + 
                                 ln_ave_arimanpf_lag * geodist_kao_tercile_med + 
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) + 
                                 log(trade_open_lag) + 
                                 inflation_lag + 
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag +
                                 exec_rc_lag + 
                                 checks_lag +
                                 (1 | year) + (1 | iso3n),
                               data = data.merge)
summary(lme.kao.arima.geo.exec)

# column (2): MSCI
lme.kao.arima.mar.exec <- lmer(kao ~ 
                                 ln_ave_arimanpf_lag * msci_kao_tercile_low + 
                                 ln_ave_arimanpf_lag * msci_kao_tercile_med + 
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) + 
                                 log(trade_open_lag) + 
                                 inflation_lag + 
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag + 
                                 exec_rc_lag +
                                 checks_lag +
                                 (1 | year) + (1 | iso3n), 
                               data = data.merge)
summary(lme.kao.arima.mar.exec)

# column (3): RATINGS
lme.kao.arima.fitch.exec <- lmer(kao ~ 
                                   ln_ave_arimanpf_lag * fitch_kao_tercile_low + 
                                   ln_ave_arimanpf_lag * fitch_kao_tercile_med + 
                                   log(gdp_const_lag) + 
                                   log(gdp_pc_const_lag) + 
                                   log(trade_open_lag) + 
                                   inflation_lag + 
                                   real_interest_rate_lag + 
                                   peg_lag + 
                                   polity2_lag + 
                                   exec_rc_lag +
                                   checks_lag +
                                   (1 | year) + (1 | iso3n),
                                 data = data.merge)
summary(lme.kao.arima.fitch.exec)

# column (4): PARTISAN Peers, full sample
lme.kao.arima.dpi <- lmer(kao ~ 
                            ln_ave_arimanpf_lag * dpi_kao_tercile_low +
                            ln_ave_arimanpf_lag * dpi_kao_tercile_med +
                            log(gdp_const_lag) + 
                            log(gdp_pc_const_lag) + 
                            log(trade_open_lag) + 
                            inflation_lag + 
                            real_interest_rate_lag + 
                            peg_lag + 
                            polity2_lag + 
                            checks_lag +
                            (1 | year) + (1 | iso3n),
                          data = data.merge)
summary(lme.kao.arima.dpi) 

# column (5): PARTISAN Peers, Right/Center governments only
lme.kao.arima.dpi.right <- lmer(kao ~
                                  ln_ave_arimanpf_lag * dpi_kao_tercile_low +
                                  ln_ave_arimanpf_lag * dpi_kao_tercile_med +
                                  log(gdp_const_lag) + 
                                  log(gdp_pc_const_lag) +
                                  log(trade_open_lag) + 
                                  inflation_lag +
                                  real_interest_rate_lag + 
                                  peg_lag + 
                                  polity2_lag +
                                  checks_lag +
                                  #(1 | year) + 
                                  (1 | iso3n),
                                data = data.merge %>% filter(exec_rc == 1))
summary(lme.kao.arima.dpi.right)

## produce tables
# set models
exec.out <- list(lme.kao.arima.geo.exec, 
                 lme.kao.arima.mar.exec, 
                 lme.kao.arima.fitch.exec,
                 lme.kao.arima.dpi,
                 lme.kao.arima.dpi.right)

# set model names
mod.names.exec <- c("GEO", "MSCI", "RATINGS", 
                    "PARTISANSHIP", "PARTISANSHIP (Right/Center)")

# set var labels
var.label.exec <- c("ln_ave_arimanpf_lag",
                    
                    "geodist_kao_tercile_low",
                    "geodist_kao_tercile_med",
                    "msci_kao_tercile_low",
                    "msci_kao_tercile_med",
                    "fitch_kao_tercile_low",
                    "fitch_kao_tercile_med",
                    "dpi_kao_tercile_low",
                    "dpi_kao_tercile_med",
                    
                    "ln_ave_arimanpf_lag:geodist_kao_tercile_low",
                    "ln_ave_arimanpf_lag:geodist_kao_tercile_med",
                    "ln_ave_arimanpf_lag:msci_kao_tercile_low",
                    "ln_ave_arimanpf_lag:msci_kao_tercile_med",
                    "ln_ave_arimanpf_lag:fitch_kao_tercile_low",
                    "ln_ave_arimanpf_lag:fitch_kao_tercile_med",
                    "ln_ave_arimanpf_lag:dpi_kao_tercile_low",
                    "ln_ave_arimanpf_lag:dpi_kao_tercile_med",
                    
                    "log(gdp_const_lag)",
                    "log(gdp_pc_const_lag)",
                    "log(trade_open_lag)",
                    "inflation_lag",
                    "real_interest_rate_lag",
                    "peg_lag",
                    "polity2_lag",
                    "checks_lag",
                    "exec_rc_lag")

# set var order
var.order.exec <- c(1:9,
                    19:26,
                    10:16, 18, 17)

#sink(file.path(MAIN_DIR, "Table-B.5.tex"))
sink(file.path(MAIN_DIR, "Table-B.5.txt"))
stargazer(exec.out,
          #type = "latex",
          type = "text",
          title = "Linear Mixed Effects Regression Results: Accounting for Partisanship",
          dep.var.labels = "Outflow Restrictions (KAO)",
          dep.var.labels.include = TRUE,
          column.labels = mod.names.exec,
          order = var.order.exec,
          covariate.labels = replaceVarName(var.vec = var.label.exec,
                                            var.df = var.df),
          add.lines = list(c("Varying Intercept: Country",
                             rep("Yes", 5)),
                           c("Varying Intercept: Year",
                             c(rep("Yes", 4), "")),
                           c("Number of Countries", 
                             formatC(n_distinct(lme.kao.arima.geo.exec@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.exec@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.exec@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.dpi@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.dpi.right@frame$iso3n), big.mark = ",")),          
                           c("Number of Years", 
                             formatC(n_distinct(lme.kao.arima.geo.exec@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.exec@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.exec@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.dpi@frame$year), big.mark = ","),
                             formatC(data.merge %>% 
                                       filter(exec_rc == 1) %>%
                                       dplyr::select(kao, 
                                                     year,
                                                     ln_ave_arimanpf_lag, 
                                                     dpi_kao_tercile_low, 
                                                     dpi_kao_tercile_med,
                                                     gdp_const_lag,
                                                     gdp_pc_const_lag,
                                                     trade_open_lag,
                                                     inflation_lag,
                                                     real_interest_rate_lag,
                                                     peg_lag,
                                                     polity2_lag,
                                                     checks) %>% 
                                       na.omit() %>%
                                       pull(year) %>%
                                       n_distinct(), big.mark = ","))),
          label = "tb:lme-exec",
          single.row = FALSE,
          column.sep.width = "0.01pt",
          no.space = TRUE,
          df = FALSE,
          font.size = "tiny",
          star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
          star.char = c("+", "*", "**", "***"),
          notes = c("The first row presents results for which peers' capital outflow restrictions are high. Standard errors in parentheses. $^{+}$p$<$0.1; $^{*}$p$<$0.05; $^{**}$p$<$0.01; $^{***}$p$<$0.001"), 
          notes.align = "l",
          notes.append = FALSE)
sink()


################################################################################
## Table B.6
## Linear Mixed Effects Regression Results: Controlling for Post-Communist Countries
################################################################################
# column (1): GEO
lme.kao.arima.geo.poco <- lmer(kao ~ 
                                 ln_ave_arimanpf_lag * geodist_kao_tercile_low + 
                                 ln_ave_arimanpf_lag * geodist_kao_tercile_med + 
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) + 
                                 log(trade_open_lag) + 
                                 inflation_lag + 
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag +
                                 checks_lag +
                                 poco_eu_fsu + 
                                 (1 | year) + (1 | iso3n),
                               data = data.merge)
summary(lme.kao.arima.geo.poco)

# column (2): MSCI
lme.kao.arima.mar.poco <- lmer(kao ~ 
                                 ln_ave_arimanpf_lag * msci_kao_tercile_low + 
                                 ln_ave_arimanpf_lag * msci_kao_tercile_med + 
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) + 
                                 log(trade_open_lag) + 
                                 inflation_lag + 
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag + 
                                 checks_lag +
                                 poco_eu_fsu +
                                 (1 | year) + (1 | iso3n), 
                               data = data.merge)
summary(lme.kao.arima.mar.poco)

# column (3): RATINGS
lme.kao.arima.fitch.poco <- lmer(kao ~ 
                                   ln_ave_arimanpf_lag * fitch_kao_tercile_low + 
                                   ln_ave_arimanpf_lag * fitch_kao_tercile_med + 
                                   log(gdp_const_lag) + 
                                   log(gdp_pc_const_lag) + 
                                   log(trade_open_lag) + 
                                   inflation_lag + 
                                   real_interest_rate_lag + 
                                   peg_lag + 
                                   polity2_lag + 
                                   checks_lag +
                                   poco_eu_fsu +
                                   (1 | year) + (1 | iso3n),
                                 data = data.merge)
summary(lme.kao.arima.fitch.poco) 

## produce tables
# set models
poco.out <- list(lme.kao.arima.geo.poco, 
                 lme.kao.arima.mar.poco, 
                 lme.kao.arima.fitch.poco)

# set model names
mod.names.poco <- c("GEO", "MSCI", "RATINGS")

# set var labels
var.label.poco <- c("ln_ave_arimanpf_lag",
                    "geodist_kao_tercile_low",
                    "geodist_kao_tercile_med",
                    "msci_kao_tercile_low",
                    "msci_kao_tercile_med",
                    "fitch_kao_tercile_low",
                    "fitch_kao_tercile_med",
                    
                    "ln_ave_arimanpf_lag:geodist_kao_tercile_low",
                    "ln_ave_arimanpf_lag:geodist_kao_tercile_med",
                    "ln_ave_arimanpf_lag:msci_kao_tercile_low",
                    "ln_ave_arimanpf_lag:msci_kao_tercile_med",
                    "ln_ave_arimanpf_lag:fitch_kao_tercile_low",
                    "ln_ave_arimanpf_lag:fitch_kao_tercile_med",
                    
                    "log(gdp_const_lag)",
                    "log(gdp_pc_const_lag)",
                    "log(trade_open_lag)",
                    "inflation_lag",
                    "real_interest_rate_lag",
                    "peg_lag",
                    "polity2_lag",
                    "checks_lag",
                    "poco_eu_fsu")

# set var order
var.order.poco <- c(1:7,
                    17:22,
                    8:16)

#sink(file.path(MAIN_DIR, "Table-B.6.tex"))
sink(file.path(MAIN_DIR, "Table-B.6.txt"))
stargazer(poco.out,
          #type = "latex",
          type = "text",
          title = "Linear Mixed Effects Regression Results: Controlling for Post-Communist Countries",
          dep.var.labels = "Outflow Restrictions (KAO)",
          dep.var.labels.include = TRUE,
          column.labels = mod.names.poco,
          order = var.order.poco,
          covariate.labels = replaceVarName(var.vec = var.label.poco,
                                            var.df = var.df),
          add.lines = list(c("Varying Intercept: Country",
                             rep("Yes", 6)),
                           c("Varying Intercept: Year",
                             rep("Yes", 6)),
                           c("Number of Countries", 
                             formatC(n_distinct(lme.kao.arima.geo.poco@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.poco@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.poco@frame$iso3n), big.mark = ",")),          
                           c("Number of Years", 
                             formatC(n_distinct(lme.kao.arima.geo.poco@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.poco@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.poco@frame$year), big.mark = ","))),
          label = "tb:lme-poco",
          single.row = FALSE,
          column.sep.width = "0.01pt",
          no.space = TRUE,
          df = FALSE,
          font.size = "tiny",
          star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
          star.char = c("+", "*", "**", "***"),
          notes = c("The first row presents results for which peers' capital outflow restrictions are high. Standard errors in parentheses. $^{+}$p$<$0.1; $^{*}$p$<$0.05; $^{**}$p$<$0.01; $^{***}$p$<$0.001"), 
          notes.align = "l",
          notes.append = FALSE)
sink()


################################################################################
## Table B.7
## Placebo Moderators: Linear Mixed Effects Regressions
################################################################################
## Global Average
# column (1): cty and year FEs
lme.kao.arima.wld.high <- lmer(kao ~ 
                                 ln_ave_arimanpf_lag * wld_kao_tercile_low + 
                                 ln_ave_arimanpf_lag * wld_kao_tercile_med + 
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) + 
                                 log(trade_open_lag) + 
                                 inflation_lag + 
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag +
                                 checks_lag + 
                                 (1 | year) + (1 | iso3n),
                               data = data.merge)
summary(lme.kao.arima.wld.high)

# column (2): cty FEs
lme.kao.arima.wld.high.c <- lmer(kao ~ 
                                   ln_ave_arimanpf_lag * wld_kao_tercile_low + 
                                   ln_ave_arimanpf_lag * wld_kao_tercile_med + 
                                   log(gdp_const_lag) + 
                                   log(gdp_pc_const_lag) + 
                                   log(trade_open_lag) + 
                                   inflation_lag + 
                                   real_interest_rate_lag + 
                                   peg_lag + 
                                   polity2_lag +
                                   checks_lag +
                                   (1 | iso3n),
                                 data = data.merge)
summary(lme.kao.arima.wld.high.c)

## Top-Growth Countries 
# column (3): cty and year FEs
lme.kao.arima.top.high <- lmer(kao ~ 
                                 ln_ave_arimanpf_lag * top_kao_tercile_low + 
                                 ln_ave_arimanpf_lag * top_kao_tercile_med + 
                                 log(gdp_const_lag) + 
                                 log(gdp_pc_const_lag) + 
                                 log(trade_open_lag) + 
                                 inflation_lag + 
                                 real_interest_rate_lag + 
                                 peg_lag + 
                                 polity2_lag +
                                 checks_lag +
                                 (1 | year) + (1 | iso3n),
                               data = data.merge)
summary(lme.kao.arima.top.high)

# column (4): cty FEs
lme.kao.arima.top.high.c <- lmer(kao ~ 
                                   ln_ave_arimanpf_lag * top_kao_tercile_low + 
                                   ln_ave_arimanpf_lag * top_kao_tercile_med + 
                                   log(gdp_const_lag) + 
                                   log(gdp_pc_const_lag) + 
                                   log(trade_open_lag) + 
                                   inflation_lag + 
                                   real_interest_rate_lag + 
                                   peg_lag + 
                                   polity2_lag +
                                   checks_lag + 
                                   (1 | iso3n),
                                 data = data.merge)
summary(lme.kao.arima.top.high.c)

## produce tables
# set models
lme.p.m.out <- list(lme.kao.arima.wld.high,
                    lme.kao.arima.wld.high.c,
                    lme.kao.arima.top.high,
                    lme.kao.arima.top.high.c)

# set model names
mod.names.p.m <- c("Global Average",
                   "Global Average",
                   "Top Growth Countries",
                   "Top Growth Countries")

# set var order
var.order.p.m <- c(1:5,
                   14:17,
                   6:13)
# set var labels
var.label.p.m <- c("ln_ave_arimanpf_lag",
                   "wld_kao_tercile_low",
                   "wld_kao_tercile_med",
                   "top_kao_tercile_low",
                   "top_kao_tercile_med",
                   
                   "ln_ave_arimanpf_lag:wld_kao_tercile_low",
                   "ln_ave_arimanpf_lag:wld_kao_tercile_med",
                   "ln_ave_arimanpf_lag:top_kao_tercile_low",
                   "ln_ave_arimanpf_lag:top_kao_tercile_med",
                   
                   "log(gdp_const_lag)",
                   "log(gdp_pc_const_lag)",
                   "log(trade_open_lag)",
                   "inflation_lag",
                   "real_interest_rate_lag",
                   "peg_lag",
                   "polity2_lag",
                   "checks_lag")

# save
sink(file.path(MAIN_DIR, "Table-B.7.txt"))
#sink(file.path(MAIN_DIR, "Table-B.7.tex"))
stargazer(lme.p.m.out,
          #type = "latex",
          type = "text",
          title = "Placebo Moderators: Linear Mixed Effects Regressions",
          dep.var.labels = "",
          dep.var.labels.include = FALSE,
          column.labels = mod.names.p.m,
          order = var.order.p.m,
          covariate.labels = replaceVarName(var.vec = var.label.p.m,
                                            var.df = var.df),
          add.lines = list(c("Varying Intercept: Country",
                             rep("Yes", 4)),
                           c("Varying Intercept: Year",
                             c("Yes", "", "Yes", "")),
                           c("Number of Countries", 
                             formatC(n_distinct(lme.kao.arima.wld.high@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.wld.high.c@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.top.high@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.top.high.c@frame$iso3n), big.mark = ",")),          
                           c("Number of Years", 
                             formatC(n_distinct(lme.kao.arima.wld.high@frame$year), big.mark = ","),
                             formatC(data.merge %>% 
                                       dplyr::select(kao, 
                                                     year,
                                                     ln_ave_arimanpf_lag, 
                                                     wld_kao_tercile_low, 
                                                     wld_kao_tercile_med,
                                                     gdp_const_lag,
                                                     gdp_pc_const_lag,
                                                     trade_open_lag,
                                                     inflation_lag,
                                                     real_interest_rate_lag,
                                                     peg_lag,
                                                     polity2_lag,
                                                     checks) %>% 
                                       na.omit() %>%
                                       pull(year) %>%
                                       n_distinct(), 
                                     big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.top.high@frame$year), big.mark = ","),
                             formatC(data.merge %>% 
                                       dplyr::select(kao, 
                                                     year,
                                                     ln_ave_arimanpf_lag, 
                                                     wld_kao_tercile_low, 
                                                     wld_kao_tercile_med,
                                                     gdp_const_lag,
                                                     gdp_pc_const_lag,
                                                     trade_open_lag,
                                                     inflation_lag,
                                                     real_interest_rate_lag,
                                                     peg_lag,
                                                     polity2_lag,
                                                     checks) %>% 
                                       na.omit() %>%
                                       pull(year) %>%
                                       n_distinct(), big.mark = ","))),
          label = "tb:placebo-moderators",
          single.row = FALSE,
          column.sep.width = "0.01pt",
          no.space = TRUE,
          df = FALSE,
          font.size = "tiny",
          star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
          star.char = c("+", "*", "**", "***"),
          notes = c("The first row presents results for which the average level of capital outflow restrictions globally or among top-growth countries are high. Standard errors in parentheses. $^{+}$p$<$0.1; $^{*}$p$<$0.05; $^{**}$p$<$0.01; $^{***}$p$<$0.001"), 
          notes.append = FALSE)
sink()


################################################################################
## Table B.8
## Linear Mixed Effects Regression Results: Conditioning on Federal Fund Rates
################################################################################
# column (1): GEO
lme.kao.arima.geo.fedrates <- lmer(kao ~
                                     ln_ave_arimanpf_lag + 
                                     geodist_kao_tercile_med + 
                                     geodist_kao_tercile_high + 
                                     fedrate_high + 
                                    
                                     ln_ave_arimanpf_lag:geodist_kao_tercile_med + 
                                     ln_ave_arimanpf_lag:geodist_kao_tercile_high +
                                     ln_ave_arimanpf_lag:fedrate_high + 
                                     fedrate_high:geodist_kao_tercile_med +
                                     fedrate_high:geodist_kao_tercile_high +
                                    
                                     ln_ave_arimanpf_lag:geodist_kao_tercile_med:fedrate_high +
                                     ln_ave_arimanpf_lag:geodist_kao_tercile_high:fedrate_high +
                                    
                                     log(gdp_const_lag) + 
                                     log(gdp_pc_const_lag) + 
                                     log(trade_open_lag) + 
                                     inflation_lag + 
                                     real_interest_rate_lag + 
                                     peg_lag + 
                                     polity2_lag +
                                     checks_lag +
                                     (1 | year) + (1 | iso3n),
                                   data = data.merge)
summary(lme.kao.arima.geo.fedrates) 

# column (2): MSCI
lme.kao.arima.mar.fedrates <- lmer(kao ~ 
                                     ln_ave_arimanpf_lag + 
                                     msci_kao_tercile_med + 
                                     msci_kao_tercile_high +
                                     fedrate_high + 
                                     
                                     ln_ave_arimanpf_lag:msci_kao_tercile_med + 
                                     ln_ave_arimanpf_lag:msci_kao_tercile_high + 
                                     ln_ave_arimanpf_lag:fedrate_high +
                                     fedrate_high:msci_kao_tercile_med +
                                     fedrate_high:msci_kao_tercile_high +
                                     
                                     ln_ave_arimanpf_lag:msci_kao_tercile_med:fedrate_high + 
                                     ln_ave_arimanpf_lag:msci_kao_tercile_high:fedrate_high + 
                                     
                                     log(gdp_const_lag) + 
                                     log(gdp_pc_const_lag) + 
                                     log(trade_open_lag) + 
                                     inflation_lag + 
                                     real_interest_rate_lag + 
                                     peg_lag + 
                                     polity2_lag +
                                     checks_lag +
                                     (1 | year) + (1 | iso3n),
                                   data = data.merge)
summary(lme.kao.arima.mar.fedrates)

# column (3): RATINGS
lme.kao.arima.fitch.fedrates <- lmer(kao ~ 
                                       ln_ave_arimanpf_lag + 
                                       fitch_kao_tercile_med +
                                       fitch_kao_tercile_high +
                                       fedrate_high + 
                                       
                                       ln_ave_arimanpf_lag:fitch_kao_tercile_med + 
                                       ln_ave_arimanpf_lag:fitch_kao_tercile_high + 
                                       ln_ave_arimanpf_lag:fedrate_high +
                                       fedrate_high:fitch_kao_tercile_med +
                                       fedrate_high:fitch_kao_tercile_high +
                                       
                                       ln_ave_arimanpf_lag:fitch_kao_tercile_med:fedrate_high + 
                                       ln_ave_arimanpf_lag:fitch_kao_tercile_high:fedrate_high + 
                                       
                                       log(gdp_const_lag) + 
                                       log(gdp_pc_const_lag) + 
                                       log(trade_open_lag) + 
                                       inflation_lag + 
                                       real_interest_rate_lag + 
                                       peg_lag + 
                                       polity2_lag +
                                       checks_lag +
                                       (1 | year) + (1 | iso3n),
                                     data = data.merge)
summary(lme.kao.arima.fitch.fedrates) 

## produce tables
# set models
triple.fedrates.out <- list(lme.kao.arima.geo.fedrates, 
                            lme.kao.arima.mar.fedrates,
                            lme.kao.arima.fitch.fedrates)

# set model names
mod.names.triple.fedrates <- c("GEO", "MSCI", "RATINGS")

# set var labels
var.label.triple.fedrates <- c("ln_ave_arimanpf_lag",
                               
                               "geodist_kao_tercile_med",
                               "geodist_kao_tercile_high",
                               "msci_kao_tercile_med",
                               "msci_kao_tercile_high",
                               "fitch_kao_tercile_med",
                               "fitch_kao_tercile_high",
                               
                               "fedrate_high",
                               
                               "ln_ave_arimanpf_lag:geodist_kao_tercile_med",
                               "ln_ave_arimanpf_lag:geodist_kao_tercile_high",
                               "ln_ave_arimanpf_lag:msci_kao_tercile_med",
                               "ln_ave_arimanpf_lag:msci_kao_tercile_high",
                               "ln_ave_arimanpf_lag:fitch_kao_tercile_med",
                               "ln_ave_arimanpf_lag:fitch_kao_tercile_high",
                               
                               "ln_ave_arimanpf_lag:fedrate_high",
                               
                               "geodist_kao_tercile_med:fedrate_high",
                               "geodist_kao_tercile_high:fedrate_high",
                               "msci_kao_tercile_med:fedrate_high",
                               "msci_kao_tercile_high:fedrate_high",
                               "fitch_kao_tercile_med:fedrate_high",
                               "fitch_kao_tercile_high:fedrate_high",
                               
                               "ln_ave_arimanpf_lag:geodist_kao_tercile_med:fedrate_high",
                               "ln_ave_arimanpf_lag:geodist_kao_tercile_high:fedrate_high",
                               "ln_ave_arimanpf_lag:msci_kao_tercile_med:fedrate_high",
                               "ln_ave_arimanpf_lag:msci_kao_tercile_high:fedrate_high",
                               "ln_ave_arimanpf_lag:fitch_kao_tercile_med:fedrate_high",
                               "ln_ave_arimanpf_lag:fitch_kao_tercile_high:fedrate_high",
                               
                               "log(gdp_const_lag)",
                               "log(gdp_pc_const_lag)",
                               "log(trade_open_lag)",
                               "inflation_lag",
                               "real_interest_rate_lag",
                               "peg_lag",
                               "polity2_lag",
                               "checks_lag")

# set var order
var.order.triple.fedrates <- c(1:8,
                               17:25,
                               28, 29,
                               32, 33,
                               26, 27, 
                               30, 31,
                               34, 35,
                               9:16)

#sink(file.path(MAIN_DIR, "Table-B.8.tex"))
sink(file.path(MAIN_DIR, "Table-B.8.txt"))
stargazer(triple.fedrates.out,
          #type = "latex",
          type = "text",
          title = "Linear Mixed Effects Regression Results: Conditioning on Federal Fund Rates",
          dep.var.labels = "Outflow Restrictions (KAO)",
          dep.var.labels.include = TRUE,
          column.labels = mod.names.triple.fedrates,
          order = var.order.triple.fedrates,
          covariate.labels = replaceVarName(var.vec = var.label.triple.fedrates,
                                            var.df = var.df),
          add.lines = list(c("Varying Intercept: Country",
                             rep("Yes", 3)),
                           c("Varying Intercept: Year",
                             rep("Yes", 3)),
                           c("Number of Countries",
                             formatC(n_distinct(lme.kao.arima.geo.fedrates@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.fedrates@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.fedrates@frame$iso3n), big.mark = ",")),
                           c("Number of Years",
                             formatC(n_distinct(lme.kao.arima.geo.fedrates@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.fedrates@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.fedrates@frame$year), big.mark = ","))),
          label = "tb:lme-triple-fedrates",
          single.row = FALSE,
          column.sep.width = "0.01pt",
          no.space = TRUE,
          df = FALSE,
          font.size = "tiny",
          star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
          star.char = c("+", "*", "**", "***"),
          notes = c("The first row presents results for which peers' capital outflow restrictions are low and when the Effective Federal Funds Rate is low. Standard errors in parentheses. $^{+}$p$<$0.1; $^{*}$p$<$0.05; $^{**}$p$<$0.01; $^{***}$p$<$0.001"), 
          notes.align = "l",
          notes.append = FALSE)
sink()


################################################################################
## Table B.9
## Linear Mixed Effects Regression Results: Conditioning on the VIX Index
################################################################################
# column (1): GEO
lme.kao.arima.geo.vix <- lmer(kao ~ 
                                ln_ave_arimanpf_lag + 
                                geodist_kao_tercile_med + 
                                geodist_kao_tercile_high + 
                                vix_high + 
                                
                                ln_ave_arimanpf_lag:geodist_kao_tercile_med + 
                                ln_ave_arimanpf_lag:geodist_kao_tercile_high +
                                ln_ave_arimanpf_lag:vix_high + 
                                vix_high:geodist_kao_tercile_med +
                                vix_high:geodist_kao_tercile_high +
                                
                                ln_ave_arimanpf_lag:geodist_kao_tercile_med:vix_high +
                                ln_ave_arimanpf_lag:geodist_kao_tercile_high:vix_high +
                                
                                log(gdp_const_lag) + 
                                log(gdp_pc_const_lag) + 
                                log(trade_open_lag) + 
                                inflation_lag + 
                                real_interest_rate_lag + 
                                peg_lag + 
                                polity2_lag +
                                checks_lag +
                                (1 | year) + (1 | iso3n),
                              data = data.merge)
summary(lme.kao.arima.geo.vix) 

# column (2): MSCI
lme.kao.arima.mar.vix <- lmer(kao ~ 
                                ln_ave_arimanpf_lag + 
                                msci_kao_tercile_med + 
                                msci_kao_tercile_high +
                                vix_high + 
                                 
                                ln_ave_arimanpf_lag:msci_kao_tercile_med + 
                                ln_ave_arimanpf_lag:msci_kao_tercile_high + 
                                ln_ave_arimanpf_lag:vix_high +
                                vix_high:msci_kao_tercile_med +
                                vix_high:msci_kao_tercile_high +
                                
                                ln_ave_arimanpf_lag:msci_kao_tercile_med:vix_high + 
                                ln_ave_arimanpf_lag:msci_kao_tercile_high:vix_high + 
                                
                                log(gdp_const_lag) + 
                                log(gdp_pc_const_lag) + 
                                log(trade_open_lag) + 
                                inflation_lag + 
                                real_interest_rate_lag + 
                                peg_lag + 
                                polity2_lag +
                                checks_lag +
                                (1 | year) + (1 | iso3n),
                              data = data.merge)
summary(lme.kao.arima.mar.vix)

# column (3): RATINGS
lme.kao.arima.fitch.vix <- lmer(kao ~ 
                                  ln_ave_arimanpf_lag + 
                                  fitch_kao_tercile_med +
                                  fitch_kao_tercile_high +
                                  vix_high + 
                                  
                                  ln_ave_arimanpf_lag:fitch_kao_tercile_med + 
                                  ln_ave_arimanpf_lag:fitch_kao_tercile_high + 
                                  ln_ave_arimanpf_lag:vix_high +
                                  vix_high:fitch_kao_tercile_med +
                                  vix_high:fitch_kao_tercile_high +
                                   
                                  ln_ave_arimanpf_lag:fitch_kao_tercile_med:vix_high + 
                                  ln_ave_arimanpf_lag:fitch_kao_tercile_high:vix_high + 
                                  
                                  log(gdp_const_lag) + 
                                  log(gdp_pc_const_lag) +
                                  log(trade_open_lag) + 
                                  inflation_lag + 
                                  real_interest_rate_lag + 
                                  peg_lag + 
                                  polity2_lag +
                                  checks_lag +
                                  (1 | year) + (1 | iso3n),
                                data = data.merge)
summary(lme.kao.arima.fitch.vix) 

## produce tables
# set models
triple.vix.out <- list(lme.kao.arima.geo.vix, 
                       lme.kao.arima.mar.vix,
                       lme.kao.arima.fitch.vix)

# set model names
mod.names.triple.vix <- c("GEO", "MSCI", "RATINGS")

# set var labels
var.label.triple.vix <- c("ln_ave_arimanpf_lag",
                          
                          "geodist_kao_tercile_med",
                          "geodist_kao_tercile_high",
                          "msci_kao_tercile_med",
                          "msci_kao_tercile_high",
                          "fitch_kao_tercile_med",
                          "fitch_kao_tercile_high",
                          
                          "vix_high",
                          
                          "ln_ave_arimanpf_lag:geodist_kao_tercile_med",
                          "ln_ave_arimanpf_lag:geodist_kao_tercile_high",
                          "ln_ave_arimanpf_lag:msci_kao_tercile_med",
                          "ln_ave_arimanpf_lag:msci_kao_tercile_high",
                          "ln_ave_arimanpf_lag:fitch_kao_tercile_med",
                          "ln_ave_arimanpf_lag:fitch_kao_tercile_high",
                          
                          "ln_ave_arimanpf_lag:vix_high",
                          
                          "geodist_kao_tercile_med:vix_high",
                          "geodist_kao_tercile_high:vix_high",
                          "msci_kao_tercile_med:vix_high",
                          "msci_kao_tercile_high:vix_high",
                          "fitch_kao_tercile_med:vix_high",
                          "fitch_kao_tercile_high:vix_high",
                          
                          "ln_ave_arimanpf_lag:geodist_kao_tercile_med:vix_high",
                          "ln_ave_arimanpf_lag:geodist_kao_tercile_high:vix_high",
                          "ln_ave_arimanpf_lag:msci_kao_tercile_med:vix_high",
                          "ln_ave_arimanpf_lag:msci_kao_tercile_high:vix_high",
                          "ln_ave_arimanpf_lag:fitch_kao_tercile_med:vix_high",
                          "ln_ave_arimanpf_lag:fitch_kao_tercile_high:vix_high",
                          
                          "log(gdp_const_lag)",
                          "log(gdp_pc_const_lag)",
                          "log(trade_open_lag)",
                          "inflation_lag",
                          "real_interest_rate_lag",
                          "peg_lag",
                          "polity2_lag",
                          "checks_lag")

# set var order
var.order.triple.vix <- c(1:8,
                          17:25,
                          28, 29,
                          32, 33,
                          26, 27, 
                          30, 31,
                          34, 35,
                          9:16)

#sink(file.path(MAIN_DIR, "Table-B.9.tex"))
sink(file.path(MAIN_DIR, "Table-B.9.txt"))
stargazer(triple.vix.out,
          #type = "latex",
          type = "text",
          title = "Linear Mixed Effects Regression Results: Conditioning on the VIX Index",
          dep.var.labels = "Outflow Restrictions (KAO)",
          dep.var.labels.include = TRUE,
          column.labels = mod.names.triple.vix,
          order = var.order.triple.vix,
          covariate.labels = replaceVarName(var.vec = var.label.triple.vix,
                                            var.df = var.df),
          add.lines = list(c("Varying Intercept: Country",
                             rep("Yes", 3)),
                           c("Varying Intercept: Year",
                             rep("Yes", 3)),
                           c("Number of Countries",
                             formatC(n_distinct(lme.kao.arima.geo.vix@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.vix@frame$iso3n), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.vix@frame$iso3n), big.mark = ",")),
                           c("Number of Years",
                             formatC(n_distinct(lme.kao.arima.geo.vix@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.mar.vix@frame$year), big.mark = ","),
                             formatC(n_distinct(lme.kao.arima.fitch.vix@frame$year), big.mark = ","))),
          label = "tb:lme-triple-vix",
          single.row = FALSE,
          column.sep.width = "0.01pt",
          no.space = TRUE,
          df = FALSE,
          font.size = "tiny",
          star.cutoffs = c(0.1, 0.05, 0.01, 0.001),
          star.char = c("+", "*", "**", "***"),
          notes = c("The first row presents results for which peers' capital outflow restrictions are low and when the VIX index is low. Standard errors in parentheses. $^{+}$p$<$0.1; $^{*}$p$<$0.05; $^{**}$p$<$0.01; $^{***}$p$<$0.001"), 
          notes.align = "l",
          notes.append = FALSE)
sink()


################################################################################
## Figure 1
## Mean Capital Flow Volatility in Twenty-Five Emerging Markets, 1995–2015
################################################################################
# study sample
em.df <- tibble(cty = c("Brazil", "Bulgaria", "Sri Lanka", "Chile", "China", 
                        "Colombia", "Costa Rica", "El Salvador", "Guatemala", "Hungary", 
                        "India", "Indonesia", "Malaysia", "Mexico", "Paraguay", 
                        "Peru", "Philippines", "Poland", "Romania", "Russia", 
                        "South Africa", "Thailand", "Ukraine", "Egypt", "Uruguay"),
                iso3n = countrycode(cty, "country.name", "iso3n"))

# extract data
cfv.df <- data.merge %>%
  filter(iso3n %in% em.df$iso3n) %>%
  dplyr::select(iso3n, year, country_name,
                ave_arimanpf) 

# summarize
cfv.emd.sum.df <- cfv.df %>%
  group_by(year) %>%
  summarize(mean = mean(ave_arimanpf, na.rm = TRUE))

# plot
axis.title.size <- 14

p.cfv.emd.mean <- ggplot(cfv.emd.sum.df, 
                         aes(x = year, 
                             y = mean)) +
  # Asian financial crisis, 97-98
  geom_rect(xmin = 1997, xmax = 1998, 
            ymin = -Inf, ymax = Inf, 
            fill = "grey90", color = "grey90",
            alpha = 0.1) +
  # Global financial crisis, 07'-09'
  geom_rect(xmin = 2007, xmax = 2009, 
            ymin = -Inf, ymax = Inf, 
            fill = "grey90", color = "grey90",
            alpha = 0.1) +
  # European debt crisis, 10'-12'
  geom_rect(xmin = 2010, xmax = 2012, 
            ymin = -Inf, ymax = Inf, 
            fill = "grey90", color = "grey90",
            alpha = 0.1) +
  geom_point(size = 2) + 
  geom_line() +  
  ggtitle("25 Emerging Markets") +
  scale_y_continuous("Mean Capital Flow Volatility",
                     limits = c(2, 4.5),
                     breaks = seq(2, 4.5, 0.5)) +
  theme_bw()  +
  theme(plot.title = element_text(size = axis.title.size + 2,
                                  face = "bold",
                                  margin = margin(0, 0, 20, 0),
                                  hjust = 0.5),
        axis.title.y = element_text(size = axis.title.size + 4,
                                    margin = margin(0, 20, 0, 0)),
        axis.title.x = element_blank(),
        axis.text = element_text(size = axis.title.size),
        panel.grid = element_blank(),
        panel.spacing = unit(1, "lines"),
        legend.position = "none") + 
  annotate("text", 
           x = 1997, 
           y = 4.45,
           label = "Asian\nFinancial\nCrisis", 
           color = "black",
           hjust = 0,
           size = 3.5) + 
  annotate("text", 
           x = 2007, 
           y = 4.45,
           label = "Global\nFinancial\nCrisis", 
           color = "black",
           hjust = 0,
           size = 3.5) +
  annotate("text", 
           x = 2010, 
           y = 4.45,
           label = "Eurpean\nDebt\nCrisis", 
           color = "black",
           hjust = 0,
           size = 3.5)

p.cfv.emd.mean

# print
pdf(file = paste(MAIN_DIR, "Fig-1.pdf", sep = "/"), 
    width = 6, height = 6)
print(p.cfv.emd.mean)
dev.off()


################################################################################
## Figure 2
## The Heterogeneous Effects of Capital Flow Volatility on Outflow Restrictions
################################################################################
# set vars to extract
vars.select.s <- c("ln_ave_arimanpf_lag")

# put results in list
fm.list.s.l <- list("KAI\nGeographic Peers" = lme.kai.arima.geo.high, 
                    "KAI\nMSCI Peers" = lme.kai.arima.mar.high, 
                    "KAI\nRatings Peers" = lme.kai.arima.fitch.high, 
                    "KAO\nGeographic Peers" = lme.kao.arima.geo.high, 
                    "KAO\nMSCI Peers" = lme.kao.arima.mar.high,
                    "KAO\nRatings Peers" = lme.kao.arima.fitch.high)

# compute and extract CI when peers are high
coef.df.s.h <- map_dfr(fm.list.s.l, function(fm){
  # compute CIs
  ci.df <- confint(fm, vars.select.s, level = 0.95)
  
  # extract
  out <- tibble(var = rownames(coef(summary(fm))),
                coef = coef(summary(fm))[,1],
                lwr = ci.df[,1],
                upr = ci.df[,2]
  )
  out <- out %>% 
    filter(var %in% vars.select.s) %>%
    mutate(var = as.character(var))
}, .id = "model")

# compute CI when peers are med/low
fm.list.s.ml <- list("KAI\nGeographic Peers" = confint(glht(lme.kai.arima.geo.high, 
                                                            linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:geodist_kai_tercile_med = 0")))$confint, 
                     "KAI\nGeographic Peers" = confint(glht(lme.kai.arima.geo.high, 
                                                            linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:geodist_kai_tercile_low = 0")))$confint,
                     "KAI\nMSCI Peers" = confint(glht(lme.kai.arima.mar.high, 
                                                      linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:msci_kai_tercile_med = 0")))$confint,
                     "KAI\nMSCI Peers" = confint(glht(lme.kai.arima.mar.high, 
                                                      linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:msci_kai_tercile_low = 0")))$confint,
                     "KAI\nRatings Peers" = confint(glht(lme.kai.arima.fitch.high, 
                                                         linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:fitch_kai_tercile_med = 0")))$confint,
                     "KAI\nRatings Peers" = confint(glht(lme.kai.arima.fitch.high, 
                                                         linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:fitch_kai_tercile_low = 0")))$confint,
                     "KAO\nGeographic Peers" = confint(glht(lme.kao.arima.geo.high, 
                                                            linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:geodist_kao_tercile_med = 0")))$confint, 
                     "KAO\nGeographic Peers" = confint(glht(lme.kao.arima.geo.high, 
                                                            linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:geodist_kao_tercile_low = 0")))$confint,
                     "KAO\nMSCI Peers" = confint(glht(lme.kao.arima.mar.high, 
                                                      linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:msci_kao_tercile_med = 0")))$confint,
                     "KAO\nMSCI Peers" = confint(glht(lme.kao.arima.mar.high, 
                                                      linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:msci_kao_tercile_low = 0")))$confint,
                     "KAO\nRatings Peers" = confint(glht(lme.kao.arima.fitch.high, 
                                                         linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:fitch_kao_tercile_med = 0")))$confint,
                     "KAO\nRatings Peers" = confint(glht(lme.kao.arima.fitch.high, 
                                                         linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:fitch_kao_tercile_low = 0")))$confint)

# extract CI when peers are med/low
coef.df.s.ml <- map_dfr(fm.list.s.ml, function(x){
  
  att.df <- attributes(x)
  
  out <- data_frame(var = att.df$dimnames[[1]],
                    coef = x[,1],
                    lwr = x[,2],
                    upr = x[,3])
}, .id = "model") 

# combine
coef.df.s <- rbind(coef.df.s.h, coef.df.s.ml) %>%
  arrange(model, var)

# calculate C.I.
coef.df.s <- coef.df.s %>%
  mutate(model = factor(model, 
                        levels = c("KAI\nGeographic Peers", 
                                   "KAI\nMSCI Peers", 
                                   "KAI\nRatings Peers",
                                   "KAO\nGeographic Peers", 
                                   "KAO\nMSCI Peers",
                                   "KAO\nRatings Peers"))) %>%
  tidyr::separate(model, into = c("dv", "peers"), sep = "\n",
                  remove = FALSE) %>%
  mutate(dv = case_when(dv == "KAI" ~ "Inflow Restrictions",
                        dv == "KAO" ~ "Outflow Restrictions",
                        TRUE ~ NA_character_)) %>%
  mutate(peers = factor(peers, levels = c("Geographic Peers", 
                                          "MSCI Peers",
                                          "Ratings Peers")),
         dv = factor(dv, levels = c("Inflow Restrictions", 
                                    "Outflow Restrictions")),
         var = factor(var, 
                      levels = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:geodist_kai_tercile_low", 
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:geodist_kai_tercile_med",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:msci_kai_tercile_low",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:msci_kai_tercile_med",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:fitch_kai_tercile_low",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:fitch_kai_tercile_med",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:geodist_kao_tercile_low",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:geodist_kao_tercile_med",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:msci_kao_tercile_low",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:msci_kao_tercile_med",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:fitch_kao_tercile_low",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:fitch_kao_tercile_med",
                                 "ln_ave_arimanpf_lag")))

# df for annotations
txt.shift.s <- 0.02
txt.pos.s <- tibble(model = coef.df.s$model,
                    var = coef.df.s$var,
                    coef = coef.df.s$upr + txt.shift.s,
                    lwr = coef.df.s$lwr,
                    upr = coef.df.s$upr,
                    peers = coef.df.s$peers,
                    dv = coef.df.s$dv,
                    label = rep(c("High", "Low", "Medium"), 6))

# plot
axis.title.size <- 16

plot.coef.s.kao <- ggplot(data = coef.df.s %>% 
                            filter(dv == "Outflow Restrictions"),
                          aes(x = var, y = coef,
                              ymin = lwr, 
                              ymax = upr)) +
  geom_pointrange(size = 0.4, 
                  fatten = 8) +
  geom_hline(yintercept = 0,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") + 
  facet_wrap(~ peers, nrow = 1, scales = "free_x") +
  scale_y_continuous("Estimated Effects of Volatility on Outflow Restrictions", 
                     labels = function(x) sprintf("%.2f", round(as.numeric(x), digits = 2)),
                     breaks = seq(-0.1, 0.1, by = 0.05),
                     limits = c(-0.15, 0.15)) +
  geom_text(data = txt.pos.s %>% 
              filter(dv == "Outflow Restrictions"),
            aes(label = label),
            size = axis.title.size - 11) +
  ggtitle("Outflow Restrictions") + 
  theme_bw() +  
  theme(legend.position = "none",
        axis.title.y = element_text(size = axis.title.size - 3,
                                    margin = margin(0, 20, 0, 0)),
        axis.text.y = element_text(size = axis.title.size - 2),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        plot.title = element_text(size = axis.title.size + 8,
                                  face = "bold",
                                  hjust = 0.5,
                                  margin = margin(20, 0, 0, 0)),
        strip.text = element_text(size = axis.title.size + 7,
                                  margin = margin(20, 0, 20, 0)),
        strip.background = element_blank(),
        panel.grid = element_blank()) 

plot.coef.s.kao

# print
pdf(file = paste(MAIN_DIR, "Fig-2.pdf", sep = "/"), 
    width = 10, height = 6)
print(plot.coef.s.kao)
dev.off()


################################################################################
## Figure 3
## Estimated Effects: Placebo Moderators
################################################################################
# set vars to extract
vars.select.p.m <- c("ln_ave_arimanpf_lag")

# put results in list
fm.list.p.m <- list("Global Average" = lme.kao.arima.wld.high, 
                    "Top Growth Countries" = lme.kao.arima.top.high)

# compute/extract CI when peers are high
coef.df.p.m <- map_dfr(fm.list.p.m, function(fm){
  # compute CIs
  ci.df <- confint(fm, vars.select.p.m, level = 0.95)
  
  # extract
  out <- tibble(var = rownames(coef(summary(fm))),
                coef = coef(summary(fm))[,1],
                lwr = ci.df[,1],
                upr = ci.df[,2])
  
  out <- out %>% 
    filter(var %in% vars.select.p.m) %>%
    mutate(var = as.character(var))
}, .id = "model")


# compute CIs when peers are med/low
fm.list.p.m.ml <- list("Global Average" = confint(glht(lme.kao.arima.wld.high, 
                                                       linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:wld_kao_tercile_med = 0")))$confint, 
                       "Global Average" = confint(glht(lme.kao.arima.wld.high, 
                                                       linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:wld_kao_tercile_low = 0")))$confint,
                       "Top Growth Countries" = confint(glht(lme.kao.arima.top.high, 
                                                             linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:top_kao_tercile_med = 0")))$confint, 
                       "Top Growth Countries" = confint(glht(lme.kao.arima.top.high, 
                                                             linfct = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:top_kao_tercile_low = 0")))$confint)

# extract CIs when peers are med/low
coef.df.p.m.ml <- map_dfr(fm.list.p.m.ml, function(x){
  
  att.df <- attributes(x)
  
  out <- tibble(var = att.df$dimnames[[1]],
                coef = x[,1],
                lwr = x[,2],
                upr = x[,3])
}, .id = "model") 

# combine
coef.df.p.m.all <- rbind(coef.df.p.m, coef.df.p.m.ml) %>%
  arrange(model, var)

# clean
coef.df.p.m.all <- coef.df.p.m.all %>%
  mutate(model = factor(model, 
                        levels = c("Global Average",
                                   "Top Growth Countries"))) %>%
  mutate(var = factor(var,
                      levels = c("ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:wld_kao_tercile_low",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:wld_kao_tercile_med",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:top_kao_tercile_low",
                                 "ln_ave_arimanpf_lag + ln_ave_arimanpf_lag:top_kao_tercile_med",
                                 "ln_ave_arimanpf_lag")))

# df for annotations
txt.shift.p.m <- 0.02
txt.pos.p.m <- tibble(model = coef.df.p.m.all$model,
                      var = coef.df.p.m.all$var,
                      coef = coef.df.p.m.all$upr + txt.shift.p.m,
                      lwr = coef.df.p.m.all$lwr,
                      upr = coef.df.p.m.all$upr,
                      label = rep(c("High", "Low", "Medium"), 2))

# plot
axis.title.size <- 16

plot.coef.p.m <- ggplot(data = coef.df.p.m.all,
                        aes(x = var, y = coef,
                            ymin = lwr, 
                            ymax = upr)) +
  geom_pointrange(size = 0.4,
                  fatten = 8) +
  geom_hline(yintercept = 0,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") + 
  facet_wrap(~ model, nrow = 1, scales = "free_x") +
  scale_y_continuous("Estimated Effects of Volatility on Outflow Restrictions", 
                     labels = function(x) sprintf("%.2f", round(as.numeric(x), digits = 2)),
                     breaks = seq(-0.1, 0.1, by = 0.05),
                     limits = c(-0.1, 0.15)) +
  geom_text(data = txt.pos.p.m,
            aes(label = label),
            size = axis.title.size - 11) +
  ggtitle("Outflow Restrictions") + 
  theme_bw() +  
  theme(legend.position = "none",
        axis.title.y = element_text(size = axis.title.size - 3,
                                    margin = margin(0, 20, 0, 0)),
        axis.text.y = element_text(size = axis.title.size - 2),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        plot.title = element_text(size = axis.title.size + 8,
                                  face = "bold",
                                  hjust = 0.5,
                                  margin = margin(20, 0, 0, 0)),
        strip.text = element_text(size = axis.title.size + 7,
                                  margin = margin(20, 0, 20, 0)),
        strip.background = element_blank(),
        panel.grid = element_blank()) 

plot.coef.p.m

# print
pdf(file = paste(MAIN_DIR, "Fig-3.pdf", sep = "/"), 
    width = 10, height = 6)
print(plot.coef.p.m)
dev.off()


################################################################################
## Figure 4
## Estimated Effects: Capital Inflow Restrictions as a Placebo Outcome
################################################################################
plot.coef.s.kai <- ggplot(data = coef.df.s %>% 
                            filter(dv == "Inflow Restrictions"),
                          aes(x = var, y = coef,
                              ymin = lwr, 
                              ymax = upr)) +
  geom_pointrange(size = 0.4,
                  fatten = 8) +
  geom_hline(yintercept = 0,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") + 
  facet_wrap(~ peers, nrow = 1, scales = "free_x") +
  scale_y_continuous("Estimated Effects of Volatility on Inflow Restrictions", 
                     labels = function(x) sprintf("%.2f", round(as.numeric(x), digits = 2)),
                     breaks = seq(-0.1, 0.1, by = 0.05),
                     limits = c(-0.15, 0.15)) +
  geom_text(data = txt.pos.s %>% 
              filter(dv == "Inflow Restrictions"),
            aes(label = label),
            size = axis.title.size - 11) +
  ggtitle("Inflow Restrictions") + 
  theme_bw() +  
  theme(legend.position = "none",
        axis.title.y = element_text(size = axis.title.size - 3,
                                    margin = margin(0, 20, 0, 0)),
        axis.text.y = element_text(size = axis.title.size - 2),
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        plot.title = element_text(size = axis.title.size + 8,
                                  face = "bold",
                                  hjust = 0.5,
                                  margin = margin(20, 0, 0, 0)),
        strip.text = element_text(size = axis.title.size + 7,
                                  margin = margin(20, 0, 20, 0)),
        strip.background = element_blank(),
        panel.grid = element_blank()) 

plot.coef.s.kai

# print
pdf(file = paste(MAIN_DIR, "Fig-4.pdf", sep = "/"), 
    width = 10, height = 6)
print(plot.coef.s.kai)
dev.off()


################################################################################
## Figure A.1
## Within-Country Correlations Between Spatial Lags
################################################################################
cor.df <- data.merge %>%
  group_by(iso3n) %>%
  summarize(`Geo vs. MSCI Peers` = cor(sl_geodist_kao_fkrsu, msci_mean_kao_lag, 
                                       use = "pairwise.complete.obs"),
            `Geo vs. Ratings Peers` = cor(sl_geodist_kao_fkrsu, sl_fitch_kao_fkrsu, 
                                          use = "pairwise.complete.obs"),
            `MSCI vs. Ratings Peers` = cor(msci_mean_kao_lag, sl_fitch_kao_fkrsu, 
                                           use = "pairwise.complete.obs"))

# reshape to long format
cor.df.l <- cor.df %>%
  gather(type, correlation, -iso3n) %>%
  mutate(type = factor(type, levels = c("Geo vs. MSCI Peers",
                                        "Geo vs. Ratings Peers",
                                        "MSCI vs. Ratings Peers")))

# plot
axis.title.size <- 14
f.cor <- ggplot(cor.df.l,
                aes(x = correlation)) + 
  geom_histogram(aes(y = ..density..), 
                 colour = "black", fill = "white") +
  geom_vline(aes(xintercept = 0), color = "red") +
  facet_wrap(~ type, ncol = 3) + 
  scale_y_continuous("Density") +
  scale_x_continuous("Correlation Coefficient") +
  ggtitle("Distribution of Within-Country Correlations") +
  theme_bw() +
  theme(plot.title = element_text(size = axis.title.size + 4,
                                  face = "bold",
                                  hjust = 0.5,
                                  margin = margin(0, 0, 20, 0)),
        axis.title.y = element_text(size = axis.title.size + 2,
                                    margin = margin(0, 20, 0, 0)),
        axis.title.x = element_text(size = axis.title.size + 2,
                                    margin = margin(20, 0, 0, 0)),
        strip.text = element_text(size = axis.title.size),
        strip.background = element_blank(),
        panel.grid = element_blank(),
        legend.position = "none")

f.cor

# print
pdf(file = paste(MAIN_DIR, "Fig-A.1.pdf", sep = "/"), width = 8, height = 4)
print(f.cor)
dev.off()


################################################################################
## Figure A.2
## Within-Country Correlations Between Fitch, Moody's, and S&P Ratings, 1995–2015
################################################################################
# calculate correlations between measures by country
cor.df <- ratings %>%
  group_by(iso3n) %>%
  summarize(`Fitch vs. Moody's` = cor(fitch_num, moodys_num, "pairwise.complete.obs"),
            `Fitch vs. S&P` = cor(fitch_num, sp_num, "pairwise.complete.obs"),
            `Moody's vs. S&P` = cor(moodys_num, sp_num, "pairwise.complete.obs")) %>%
  ungroup()

# check average cor
mean(cor.df$`Fitch vs. Moody's`, na.rm = TRUE)
mean(cor.df$`Fitch vs. S&P`, na.rm = TRUE)
mean(cor.df$`Moody's vs. S&P`, na.rm = TRUE)

# reshape to long format
cor.df.l <- cor.df %>%
  gather(type, correlation, -iso3n) %>%
  mutate(type = factor(type, levels = c("Fitch vs. Moody's",
                                        "Fitch vs. S&P",
                                        "Moody's vs. S&P")))

# create annotation df
text.df <- tibble(
  x = c(0.25, -0.04, -0.03),
  y = c(7, 7, 7),
  label = paste("Mean Cor. = ",
                c(round(mean(cor.df$`Fitch vs. Moody's`, na.rm = TRUE), 2),
                  round(mean(cor.df$`Fitch vs. S&P`, na.rm = TRUE), 2),
                  round(mean(cor.df$`Moody's vs. S&P`, na.rm = TRUE), 2)),
                sep = ""),
  type = factor(c("Fitch vs. Moody's",
                  "Fitch vs. S&P",
                  "Moody's vs. S&P"),
                levels = c("Fitch vs. Moody's",
                           "Fitch vs. S&P",
                           "Moody's vs. S&P")))

# plot
axis.title.size <- 14

f.cor <- ggplot(cor.df.l,
                aes(x = correlation)) + 
  geom_histogram(aes(y = ..density..), 
                 colour = "black", fill = "white") +
  geom_vline(data = cor.df.l %>% filter(type == "Fitch vs. Moody's"),
             aes(xintercept = mean(cor.df$`Fitch vs. Moody's`, na.rm = TRUE)), 
             color = "red") +
  geom_vline(data = cor.df.l %>% filter(type == "Fitch vs. S&P"),
             aes(xintercept = mean(cor.df$`Fitch vs. S&P`, na.rm = TRUE)), 
             color = "red") +
  geom_vline(data = cor.df.l %>% filter(type == "Moody's vs. S&P"),
             aes(xintercept = mean(cor.df$`Moody's vs. S&P`, na.rm = TRUE)), 
             color = "red") +
  facet_wrap(~ type, ncol = 3) + 
  geom_text(data = text.df,
            aes(x = x, y = y, label = label), size = 4) +
  scale_y_continuous("Density") +
  scale_x_continuous("Correlation Coefficient") +
  ggtitle("Distribution of Within-Country Correlations") +
  theme_bw() +
  theme(plot.title = element_text(size = axis.title.size + 4,
                                  face = "bold",
                                  hjust = 0.5,
                                  margin = margin(0, 0, 20, 0)),
        axis.title.y = element_text(size = axis.title.size + 2,
                                    margin = margin(0, 20, 0, 0)),
        axis.title.x = element_text(size = axis.title.size + 2,
                                    margin = margin(20, 0, 0, 0)),
        strip.text = element_text(size = axis.title.size),
        strip.background = element_blank(),
        panel.grid = element_blank(),
        legend.position = "none",
        aspect.ratio = 1)

f.cor

# print
pdf(file = paste(MAIN_DIR, "Fig-A.2.pdf", sep = "/"), 
    width = 8, height = 4)
print(f.cor)
dev.off()


################################################################################
## Figure A.3
## Capital Outflow Restrictiveness: 25 Emerging Markets and Their Peers, 1995–2015
################################################################################
# subset data
kao.df <- data.merge %>%
  filter(iso3n %in% em.df$iso3n) %>%
  dplyr::select(iso3n, year, country_name, 
                kao, 
                sl_geodist_kao_fkrsu,
                msci_mean_kao_lag,
                sl_fitch_kao_fkrsu) %>%
  mutate(year = as.integer(year))

# reshape
kao.df.l <- kao.df %>%
  rename(`Emerging Market` = kao,
         `GEO Peers` = sl_geodist_kao_fkrsu,
         `MSCI Peers` = msci_mean_kao_lag,
         `RATINGS Peers` = sl_fitch_kao_fkrsu) %>%
  pivot_longer(cols = `Emerging Market`:`RATINGS Peers`,
               names_to = "Measure",
               values_to = "value") %>%
  mutate(Measure = factor(Measure, 
                      levels = c("Emerging Market", "GEO Peers", "MSCI Peers", "RATINGS Peers")))

# set parameters
axis.title.size <- 14
ribbon.alpha <- 0.1
colors <- c("black", # kao
            "#4DAF4A", # geo
            "#377EB8", # msci
            "#E41A1C" # ratings
)
shapes <- c(16, # kao
            0, # geo
            2, # msci
            5 # ratings
)

# plot
p.kao.emd <- ggplot(kao.df.l, 
                    aes(x = year, 
                        y = value,
                        group = Measure,
                        color = Measure,
                        shape = Measure)) +
  geom_line(size = 0.4) +
  geom_point(size = 1.5) +
  scale_color_manual(values = colors) +
  scale_shape_manual(values = shapes) +
  facet_wrap(~ as.factor(country_name), nrow = 5) + 
  scale_y_continuous("Capital Outflow Restrictiveness (KAO)") +
  ggtitle("25 Emerging Markets") +
  theme_bw()  +
  theme(plot.title = element_text(size = axis.title.size + 10,
                                  face = "bold",
                                  margin = margin(0, 0, 20, 0),
                                  hjust = 0.5),
        panel.spacing = unit(1, "lines"),
        axis.title.y = element_text(size = axis.title.size + 10,
                                    margin = margin(0, 20, 0, 0)),
        axis.title.x = element_blank(),
        axis.text = element_text(size = axis.title.size - 2),
        strip.text = element_text(size = axis.title.size + 4),
        strip.background = element_blank(),
        panel.grid = element_blank(),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.title = element_blank(),
        legend.text = element_text(size = axis.title.size + 4))

p.kao.emd

# print
pdf(file = paste(MAIN_DIR, "Fig-A.3.pdf", sep = "/"), 
    width = 12, height = 14)
print(p.kao.emd)
dev.off()


################################################################################
## Figure A.4 
## Average Capital Outflow Restrictiveness by Group, 1995–2015
################################################################################
## Left Panel: 25 Emerging Markets
# compute mean
kao.mean.df <- kao.df %>%
  group_by(year) %>%
  summarize(mean = mean(kao, na.rm = TRUE))

# set parameters
axis.title.size <- 14

# plot
p.kao.em.25.mean <- ggplot(kao.mean.df, 
                           aes(x = year, 
                               y = mean)) +
  geom_line(size = 0.4) +
  geom_point(size = 2) + 
  scale_y_continuous("Mean Capital Outflow Restrictiveness (KAO)",
                     limit = c(0.35, 0.757),
                     breaks = seq(0.35, 0.75, 0.1)
                     ) +
  ggtitle("25 Emerging Markets") +
  theme_bw()  +
  theme(plot.title = element_text(size = axis.title.size + 4,
                                  face = "bold",
                                  margin = margin(0, 0, 20, 0),
                                  hjust = 0.5),
        panel.spacing = unit(1, "lines"),
        axis.title.y = element_text(size = axis.title.size + 4,
                                    margin = margin(0, 20, 0, 0)),
        axis.title.x = element_blank(),
        axis.text = element_text(size = axis.title.size),
        strip.text = element_text(size = axis.title.size + 4),
        strip.background = element_blank(),
        panel.grid = element_blank())

p.kao.em.25.mean

## Center Panel: World
# extract data
kao.wld.mean.df <- data.merge %>%
  filter(iso3n %in% em.df$iso3n) %>%
  dplyr::select(iso3n, year, country_name, 
                kao, 
                kao_wld) %>%
  mutate(year = as.integer(year)) %>%
  dplyr::select(year, kao_wld) %>%
  distinct() # does not vary by country

# set parameters
axis.title.size <- 14

# plot
p.kao.wld.mean <- ggplot(kao.wld.mean.df, 
                         aes(x = year, 
                             y = kao_wld)) +
  geom_line(size = 0.4) +
  geom_point(size = 2) + 
  scale_y_continuous("",
                     limit = c(0.35, 0.757),
                     breaks = seq(0.35, 0.75, 0.1)) +
  ggtitle("World") +
  theme_bw()  +
  theme(plot.title = element_text(size = axis.title.size + 4,
                                  face = "bold",
                                  margin = margin(0, 0, 20, 0),
                                  hjust = 0.5),
        panel.spacing = unit(1, "lines"),
        axis.title.y = element_text(size = axis.title.size + 4,
                                    margin = margin(0, 20, 0, 0)),
        axis.title.x = element_blank(),
        axis.text = element_text(size = axis.title.size),
        strip.text = element_text(size = axis.title.size + 4),
        strip.background = element_blank(),
        panel.grid = element_blank())

p.kao.wld.mean

## Right Panel: Top-Growth Countries
# extract data
kao.top.mean.df <- data.merge %>%
  filter(iso3n %in% em.df$iso3n) %>%
  dplyr::select(iso3n, year, country_name, 
                top_g_decile_kao) %>%
  mutate(year = as.integer(year)) %>%
  dplyr::select(year, top_g_decile_kao) %>%
  distinct() # does not vary by country

# set parameters
axis.title.size <- 14

# plot
p.kao.top.mean <- ggplot(kao.top.mean.df, 
                         aes(x = year, 
                             y = top_g_decile_kao)) +
  geom_line(size = 0.4) +
  geom_point(size = 2) + 
  scale_y_continuous("",
                     limit = c(0.35, 0.757),
                     breaks = seq(0.35, 0.75, 0.1)) +
  xlab("Year") +
  ggtitle("Top-Growth Countries") +
  theme_bw()  +
  theme(plot.title = element_text(size = axis.title.size + 4,
                                  face = "bold",
                                  margin = margin(0, 0, 20, 0),
                                  hjust = 0.5),
        panel.spacing = unit(1, "lines"),
        axis.title.y = element_text(size = axis.title.size + 4,
                                    margin = margin(0, 20, 0, 0)),
        axis.title.x = element_blank(),
        axis.text = element_text(size = axis.title.size),
        strip.text = element_text(size = axis.title.size + 4),
        strip.background = element_blank(),
        panel.grid = element_blank())

p.kao.top.mean

# combine and save
pdf(file = paste(MAIN_DIR, "Fig-A.4.pdf", sep = "/"), 
    width = 18, height = 6)
grid.arrange(p.kao.em.25.mean, p.kao.wld.mean, p.kao.top.mean,
             nrow = 1)
dev.off()


################################################################################
## Figure A.5
## Capital Flow Volatility in 25 Emerging Markets, 1995–2015.
################################################################################
# extract data
cfv.df <- data.merge %>%
  filter(iso3n %in% em.df$iso3n) %>%
  dplyr::select(iso3n, year, country_name,
                ave_arimanpf) 

# plot
axis.title.size <- 14

p.cfv.emd <- ggplot(cfv.df, 
                    aes(x = year, 
                        y = ave_arimanpf)) +
  geom_point(size = 1.5) +
  geom_line() + 
  facet_wrap(~ factor(country_name), nrow = 5) +
  ggtitle("25 Emerging Markets") +
  scale_y_continuous("Capital Flow Volatility") +
  theme_bw()  +
  theme(plot.title = element_text(size = axis.title.size + 10,
                                  face = "bold",
                                  margin = margin(0, 0, 20, 0),
                                  hjust = 0.5),
        panel.spacing = unit(1, "lines"),
        axis.title.y = element_text(size = axis.title.size + 10,
                                    margin = margin(0, 20, 0, 0)),
        axis.title.x = element_blank(),
        axis.text = element_text(size = axis.title.size - 2),
        strip.text = element_text(size = axis.title.size + 4),
        strip.background = element_blank(),
        panel.grid = element_blank(),
        legend.position = "bottom",
        legend.direction = "horizontal",
        legend.title = element_blank(),
        legend.text = element_text(size = axis.title.size + 4))

p.cfv.emd

# print
pdf(file = paste(MAIN_DIR, "Fig-A.5.pdf", sep = "/"), 
    width = 12, height = 12)
print(p.cfv.emd)
dev.off()


################################################################################
## Fig. C.1
## The Predicted Effect of Capital Flow Volatility on Capital Outflow 
## Restrictions When Geographic Peers' Restrictions are High
################################################################################
# 25 EMDs
em.df$iso3n

# subset
sim.df <- data.merge %>%
  filter(iso3n %in% em.df$iso3n)

# check country name
sim.df %>%
  pull(country_name) %>%
  unique() %>%
  sort()
  
# set key var range
key.var.length <- 50

# 2 sd above/below mean
range.key <- seq(ifelse((mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) -
                           2 * sd(sim.df$ave_arimanpf_lag, na.rm = TRUE)) < 0, 
                        min(sim.df$ave_arimanpf_lag, na.rm = TRUE)),
                 mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) +
                   2 * sd(sim.df$ave_arimanpf_lag, na.rm = TRUE),
                 length.out = key.var.length)
range.key

# set parameters
fm <- lme.kao.arima.geo.high
change.var <- "ln_ave_arimanpf_lag"
range.key <- range.key
n.draws <- 1000

# set seed for simulation
seed <- 1234
set.seed(seed)

# load library to draw from multivariate normal
library(MASS)
beta.draws <- mvrnorm(n.draws, coef(summary(fm))[,1], vcov(fm))

X <- getME(fm, "X")
Zt <- getME(fm, "Zt")
z.b <- crossprod(as.matrix(Zt), as.matrix(replicate(n.draws, unlist(ranef(fm)))))

# for each value of the change var
sim.out.geo <- map_dfr(1:length(range.key), function(x){
  # print
  cat(paste("Simulating expected values for ", x, " of ", 
            length(range.key), " ", change.var, " values \n",
            sep = ""))
  
  # create temp data
  newX <- X
  
  # replace change var value x
  newX[,change.var] <- log(range.key[[x]])
  
  # set values at geodist_kao_tercile_high == 1
  newX[,"geodist_kao_tercile_low"] <- 0
  newX[,"geodist_kao_tercile_med"] <- 0
  newX[,"ln_ave_arimanpf_lag:geodist_kao_tercile_low"] <- 0
  newX[,"ln_ave_arimanpf_lag:geodist_kao_tercile_med"] <- 0
  
  # matrix multiplication for the systematic component
  sys.com <- as.matrix(tcrossprod(as.matrix(newX), beta.draws))
  
  # add RE
  lp <- sys.com + z.b
  
  # average over observations for each draw
  ev <- as.data.frame(lp) %>%
    summarise_all(list(mean))
  
  # add set identifier
  sim.out <- ev %>%
    gather(draw, ev) %>%
    mutate(setx = range.key[[x]],
           draw = str_replace_all(draw, "V", ""))
  
  return(sim.out)
})

# calculate expected value 
ev.geo <- sim.out.geo %>%
  group_by(setx) %>%
  summarize(mean = mean(ev, na.rm = TRUE),
            lwr = quantile(ev, probs = 0.025),
            upr = quantile(ev, probs = 0.975))

# get distribution data
dist.fm <- fm@frame

# clean distribution data
dist.fm <- dist.fm %>%
  filter(ln_ave_arimanpf_lag <= log(max(range.key))) %>%
  mutate(setx = exp(ln_ave_arimanpf_lag))

# set parameters
axis.title.size <- 14
ribbon.alpha <- 0.1

# plot upper panel
p.ev.geo <- ggplot(ev.geo,
                   aes(x = setx, 
                       y = mean)) +
  geom_ribbon(aes(ymin = lwr,
                  ymax = upr),
              alpha = ribbon.alpha) +
  geom_line(size = 0.4) +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) -
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.014,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.05,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) +
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.086,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  ggtitle("High Capital Outflow Restrictions Among Geographic Peers") + 
  scale_x_continuous("Capital Flow Volatility") +
  scale_y_continuous("Predicted Level of Emerging Market's Outflow Restrictions") +
  theme_bw() +
  theme(plot.title = element_text(size = axis.title.size + 1,
                                  face = "bold",
                                  margin = margin(0, 0, 20, 0),
                                  hjust = 0.5),
        axis.title.x = element_text(size = axis.title.size,
                                    margin = margin(20, 0, 0, 0)),
        axis.title.y = element_text(size = axis.title.size - 3,
                                    margin = margin(0, 20, 0, 0)),
        strip.text = element_text(size = axis.title.size + 2),
        plot.margin = margin(1, 0.2, -1.7, 0.4, unit = "cm"),
        strip.background = element_blank(),
        panel.grid.minor = element_blank(),
        legend.justification = "top")

p.ev.geo

# plot bottom panel
p.marginal.geo <- ggplot(dist.fm, 
                         aes(x = setx, y = ..density..)) + 
  geom_density(alpha = .5,
               fill = "blue") + 
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) -
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) +
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  scale_x_continuous("Capital Flow Volatility") +
  scale_y_continuous("Density \n",
                     breaks = seq(0, 0.3, 0.1),
                     labels = format(seq(0, 0.3, 0.1),
                                     nsmall = 1,
                                     scientific = FALSE),
                     limits = c(0, 0.3)) +
  theme_bw() +
  theme(legend.position = c(0.922, 0.76),
        legend.key.height = unit(0.01, "cm"),
        legend.key = element_rect(fill = "transparent", 
                                  colour = "transparent",
                                  size = 0.1),
        legend.title = element_text(size = axis.title.size - 6), 
        axis.title.x = element_text(size = axis.title.size, 
                                    margin = margin(20, 0, 0, 0)),
        axis.title.y = element_text(size = axis.title.size - 3, 
                                    margin = margin(0, 7.1, 0, 0)),
        strip.text = element_text(size = 0),
        strip.background = element_blank(),
        plot.margin = margin(0, 0.2, 0.2, 0.435, unit = "cm"),
        panel.grid = element_blank()) + 
  annotate("text", 
           x = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.1, 
           y = 0.25, 
           label = "mean",
           hjust = 0) +
  annotate("text", x = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) +
             sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.1, 
           y = 0.25, 
           label = "+1 s.d.",
           hjust = 0) +
  annotate("text", x = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) -
             sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.1, 
           y = 0.25, 
           label = "-1 s.d.",
           hjust = 0)

p.marginal.geo

# combine and save
pdf(file = paste(MAIN_DIR, "Fig-C.1.pdf", sep = "/"), 
    width = 7, height = 7)
grid.arrange(p.ev.geo, p.marginal.geo, 
             ncol = 1, heights = c(2, 0.8))
dev.off()

# check DV sd
summary(sim.df$kao)
sd(sim.df$kao) # 0.3946044

# mean
mean(sim.df$ave_arimanpf_lag, na.rm = TRUE)

# mean - 1sd
mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) - sd(sim.df$ave_arimanpf_lag, na.rm = TRUE)

# mean + 1sd
mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) + sd(sim.df$ave_arimanpf_lag, na.rm = TRUE)

# increase CFV from 1 sd below mean to above, KAO increases by approx. 0.11 (0.27 sd)
ev.geo[36, "mean"] - ev.geo[6, "mean"]
(ev.geo[36, "mean"] - ev.geo[6, "mean"])/sd(sim.df$kao)


################################################################################
## Fig. C.2
## The Predicted Effect of Capital Flow Volatility on Capital Outflow 
## Restrictions When MSCI Peers' Restrictions are High
################################################################################
# set parameters
fm <- lme.kao.arima.mar.high
change.var <- "ln_ave_arimanpf_lag"
range.key <- range.key
n.draws <- 1000

# set seed for simulation
seed <- 1234
set.seed(seed)

# load library to draw from multivariate normal
library(MASS)
beta.draws <- mvrnorm(n.draws, coef(summary(fm))[,1], vcov(fm))

X <- getME(fm, "X")
Zt <- getME(fm, "Zt")
z.b <- crossprod(as.matrix(Zt), as.matrix(replicate(n.draws, unlist(ranef(fm)))))

# for each value of change var
sim.out.msci <- map_dfr(1:length(range.key), function(x){
  # print
  cat(paste("Simulating expected values for ", x, " of ", 
            length(range.key), " ", change.var, " values \n",
            sep = ""))
  
  # create temp data
  newX <- X
  
  # replace change var value x
  newX[,change.var] <- log(range.key[[x]])
  
  # set values at fitch_kao_tercile_high == 1
  newX[,"msci_kao_tercile_low"] <- 0
  newX[,"msci_kao_tercile_med"] <- 0
  newX[,"ln_ave_arimanpf_lag:msci_kao_tercile_low"] <- 0
  newX[,"ln_ave_arimanpf_lag:msci_kao_tercile_med"] <- 0
  
  # matrix multiplication for the systematic component
  sys.com <- as.matrix(tcrossprod(as.matrix(newX), beta.draws))
  
  # add RE
  lp <- sys.com + z.b
  
  # average over observations for each draw
  ev <- as.data.frame(lp) %>%
    summarise_all(list(mean))
  
  # add set identifier
  sim.out <- ev %>%
    gather(draw, ev) %>%
    mutate(setx = range.key[[x]],
           draw = str_replace_all(draw, "V", ""))
  
  return(sim.out)
})

# calculate expected value 
ev.msci <- sim.out.msci %>%
  group_by(setx) %>%
  summarize(mean = mean(ev, na.rm = TRUE),
            lwr = quantile(ev, probs = 0.025),
            upr = quantile(ev, probs = 0.975))

# get distribution data
dist.fm <- fm@frame

# clean distribution data
dist.fm <- dist.fm %>%
  filter(ln_ave_arimanpf_lag <= log(max(range.key))) %>%
  mutate(setx = exp(ln_ave_arimanpf_lag))

# set parameters
axis.title.size <- 14
ribbon.alpha <- 0.1

# plot upper panel
p.ev.msci <- ggplot(ev.msci,
                    aes(x = setx, 
                        y = mean)) +
  geom_ribbon(aes(ymin = lwr,
                  ymax = upr),
              alpha = ribbon.alpha) +
  geom_line(size = 0.4) +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) -
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.014,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.05,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) +
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.0855,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  ggtitle("High Capital Outflow Restrictions Among MSCI Peers") + 
  scale_x_continuous("Capital Flow Volatility") +
  scale_y_continuous("Predicted Level of Emerging Market's Outflow Restrictions") +
  theme_bw() +
  theme(plot.title = element_text(size = axis.title.size + 1,
                                  face = "bold",
                                  margin = margin(0, 0, 20, 0),
                                  hjust = 0.5),
        axis.title.x = element_text(size = axis.title.size,
                                    margin = margin(20, 0, 0, 0)),
        axis.title.y = element_text(size = axis.title.size - 3,
                                    margin = margin(0, 20, 0, 0)),
        strip.text = element_text(size = axis.title.size + 2),
        plot.margin = margin(1, 0.2, -1.7, 0.4, unit = "cm"),
        strip.background = element_blank(),
        panel.grid.minor = element_blank(),
        legend.justification = "top")

p.ev.msci

# plot bottom panel
p.marginal.msci <- ggplot(dist.fm, 
                          aes(x = setx, y = ..density..)) + 
  geom_density(alpha = .5,
               fill = "blue") + 
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) +
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) -
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  scale_x_continuous("Capital Flow Volatility") +
  scale_y_continuous("Density \n",
                     breaks = seq(0, 0.3, 0.1),
                     labels = format(seq(0, 0.3, 0.1),
                                     nsmall = 1,
                                     scientific = FALSE),
                     limits = c(0, 0.3)) +
  theme_bw() +
  theme(legend.position = c(0.922, 0.76),
        legend.key.height = unit(0.01, "cm"),
        legend.key = element_rect(fill = "transparent", 
                                  colour = "transparent",
                                  size = 0.1),
        legend.title = element_text(size = axis.title.size - 6), 
        axis.title.x = element_text(size = axis.title.size, 
                                    margin = margin(20, 0, 0, 0)),
        axis.title.y = element_text(size = axis.title.size - 3, 
                                    margin = margin(0, 7.1, 0, 0)),
        strip.text = element_text(size = 0),
        strip.background = element_blank(),
        plot.margin = margin(0, 0.2, 0.2, 0.435, unit = "cm"),
        panel.grid = element_blank()) + 
  annotate("text", 
           x = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.1, 
           y = 0.25, 
           label = "mean",
           hjust = 0) +
  annotate("text", x = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) +
             sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.1, 
           y = 0.25, 
           label = "+1 s.d.",
           hjust = 0) +
  annotate("text", x = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) -
             sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.1, 
           y = 0.25, 
           label = "-1 s.d.",
           hjust = 0)

p.marginal.msci

# combine and save
pdf(file = paste(MAIN_DIR, "Fig-C.2.pdf", sep = "/"), 
    width = 7, height = 7)
grid.arrange(p.ev.msci, p.marginal.msci, 
             ncol = 1, heights = c(2, 0.8))
dev.off()

# check DV sd
summary(sim.df$kao)
sd(sim.df$kao)

# mean
mean(sim.df$ave_arimanpf_lag, na.rm = TRUE)

# mean - 1sd
mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) - sd(sim.df$ave_arimanpf_lag, na.rm = TRUE)

# mean + 1sd
mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) + sd(sim.df$ave_arimanpf_lag, na.rm = TRUE)

# increase CFV from 1 sd below mean to above, KAO increases by approx. 0.07 (0.18 sd)
ev.msci[36, "mean"] - ev.msci[6, "mean"]
(ev.msci[36, "mean"] - ev.msci[6, "mean"])/sd(sim.df$kao)


################################################################################
## Fig. C.3
## The Predicted Effect of Capital Flow Volatility on Capital Outflow 
## Restrictions When Ratings Peers' Restrictions are High
################################################################################
# set parameters
fm <- lme.kao.arima.fitch.high
change.var <- "ln_ave_arimanpf_lag"
range.key <- range.key
n.draws <- 1000

# set seed for simulation
seed <- 1234
set.seed(seed)

# load library to draw from multivariate normal
library(MASS)
beta.draws <- mvrnorm(n.draws, coef(summary(fm))[,1], vcov(fm))

X <- getME(fm, "X")
Zt <- getME(fm, "Zt")
z.b <- crossprod(as.matrix(Zt), as.matrix(replicate(n.draws, unlist(ranef(fm)))))

# for each value of change var
sim.out.ratings <- map_dfr(1:length(range.key), function(x){
  # print
  cat(paste("Simulating expected values for ", x, " of ", 
            length(range.key), " ", change.var, " values \n",
            sep = ""))
  
  # create temp data
  newX <- X
  
  # replace change var value x
  newX[,change.var] <- log(range.key[[x]])
  
  # set values at fitch_kao_tercile_high == 1
  newX[,"fitch_kao_tercile_low"] <- 0
  newX[,"fitch_kao_tercile_med"] <- 0
  newX[,"ln_ave_arimanpf_lag:fitch_kao_tercile_low"] <- 0
  newX[,"ln_ave_arimanpf_lag:fitch_kao_tercile_med"] <- 0
  
  # matrix multiplication for the systematic component
  sys.com <- as.matrix(tcrossprod(as.matrix(newX), beta.draws))
  
  # add RE
  lp <- sys.com + z.b
  
  # average over observations for each draw
  ev <- as.data.frame(lp) %>%
    summarise_all(list(mean))
  
  # add set identifier
  sim.out <- ev %>%
    gather(draw, ev) %>%
    mutate(setx = range.key[[x]],
           draw = str_replace_all(draw, "V", ""))
  
  return(sim.out)
})

# calculate expected value 
ev.ratings <- sim.out.ratings %>%
  group_by(setx) %>%
  summarize(mean = mean(ev, na.rm = TRUE),
            lwr = quantile(ev, probs = 0.025),
            upr = quantile(ev, probs = 0.975))

# get distribution data
dist.fm <- fm@frame

# clean distribution data
dist.fm <- dist.fm %>%
  filter(ln_ave_arimanpf_lag <= log(max(range.key))) %>%
  mutate(setx = exp(ln_ave_arimanpf_lag))

# set parameters
axis.title.size <- 14
ribbon.alpha <- 0.1

# plot upper panel
p.ev.ratings <- ggplot(ev.ratings,
                       aes(x = setx, 
                           y = mean)) +
  geom_ribbon(aes(ymin = lwr,
                  ymax = upr),
              alpha = ribbon.alpha) +
  geom_line(size = 0.4) +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) -
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) - 0.028,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.023,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) +
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.072,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  ggtitle("High Capital Outflow Restrictions Among Ratings Peers") + 
  scale_x_continuous("Capital Flow Volatility") +
  scale_y_continuous("Predicted Level of Emerging Market's Outflow Restrictions") +
  theme_bw() +
  theme(plot.title = element_text(size = axis.title.size + 1,
                                  face = "bold",
                                  margin = margin(0, 0, 20, 0),
                                  hjust = 0.5),
        axis.title.x = element_text(size = axis.title.size,
                                    margin = margin(20, 0, 0, 0)),
        axis.title.y = element_text(size = axis.title.size - 3,
                                    margin = margin(0, 20, 0, 0)),
        strip.text = element_text(size = axis.title.size + 2),
        plot.margin = margin(1, 0.2, -1.7, 0.4, unit = "cm"),
        strip.background = element_blank(),
        panel.grid.minor = element_blank(),
        legend.justification = "top")

p.ev.ratings

# plot bottom panel
p.marginal.ratings <- ggplot(dist.fm, 
                             aes(x = setx, y = ..density..)) + 
  geom_density(alpha = .5,
               fill = "blue") + 
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) +
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) -
               sd(sim.df$ave_arimanpf_lag, na.rm = TRUE),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  scale_x_continuous("Capital Flow Volatility") +
  scale_y_continuous("Density \n",
                     breaks = seq(0, 0.3, 0.1),
                     labels = format(seq(0, 0.3, 0.1),
                                     nsmall = 1,
                                     scientific = FALSE),
                     limits = c(0, 0.3)) +
  theme_bw() +
  theme(legend.position = c(0.922, 0.76),
        legend.key.height = unit(0.01, "cm"),
        legend.key = element_rect(fill = "transparent", 
                                  colour = "transparent",
                                  size = 0.1),
        legend.title = element_text(size = axis.title.size - 6), 
        axis.title.x = element_text(size = axis.title.size, 
                                    margin = margin(20, 0, 0, 0)),
        axis.title.y = element_text(size = axis.title.size - 3, 
                                    margin = margin(0, 7.1, 0, 0)),
        strip.text = element_text(size = 0),
        strip.background = element_blank(),
        plot.margin = margin(0, 0.2, 0.2, 0.435, unit = "cm"),
        panel.grid = element_blank()) + 
  annotate("text", 
           x = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.1, 
           y = 0.25, 
           label = "mean",
           hjust = 0) +
  annotate("text", x = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) +
             sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.1, 
           y = 0.25, 
           label = "+1 s.d.",
           hjust = 0) +
  annotate("text", x = mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) -
             sd(sim.df$ave_arimanpf_lag, na.rm = TRUE) + 0.1, 
           y = 0.25, 
           label = "-1 s.d.",
           hjust = 0)

p.marginal.ratings

# save
pdf(file = paste(MAIN_DIR, "Fig-C.3.pdf", sep = "/"), 
    width = 7, height = 7)
grid.arrange(p.ev.ratings, p.marginal.ratings, 
             ncol = 1, heights = c(2, 0.8))
dev.off()

# check DV sd
summary(sim.df$kao)
sd(sim.df$kao)

# mean
mean(sim.df$ave_arimanpf_lag, na.rm = TRUE)

# mean - 1sd
mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) - sd(sim.df$ave_arimanpf_lag, na.rm = TRUE)

# mean + 1sd
mean(sim.df$ave_arimanpf_lag, na.rm = TRUE) + sd(sim.df$ave_arimanpf_lag, na.rm = TRUE)

# increase CFV from 1 sd below mean to above, KAO increases by approx 0.12 (0.31 sd)
ev.ratings[36, "mean"] - ev.ratings[6, "mean"]
(ev.ratings[36, "mean"] - ev.ratings[6, "mean"])/sd(sim.df$kao)


################################################################################
## Fig. C.4
## The Predicted Effect of Log GDP Per Capita on Capital Outflow Restrictions
################################################################################
# set key var range
key.var.length <- 50

# 2 sd above/below mean
range.key <- seq(ifelse((mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) -
                           2 * sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE)) < 0, 
                        min(log(sim.df$gdp_pc_const_lag), na.rm = TRUE),
                        (mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) -
                           2 * sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE))),
                 mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) +
                   2 * sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE),
                 length.out = key.var.length)
range.key

# set parameters
fm <- lme.kao.arima.fitch.high
change.var <- "log(gdp_pc_const_lag)"
range.key <- range.key
n.draws <- 1000

# set seed for simulation
seed <- 1234
set.seed(seed)

# load library to draw from multivariate normal
library(MASS)
beta.draws <- mvrnorm(n.draws, coef(summary(fm))[,1], vcov(fm))

X <- getME(fm, "X")
Zt <- getME(fm, "Zt")
z.b <- crossprod(as.matrix(Zt), as.matrix(replicate(n.draws, unlist(ranef(fm)))))

# for each value of change var
sim.out.gdp.pc <- map_dfr(1:length(range.key), function(x){
  # print
  cat(paste("Simulating expected values for ", x, " of ", 
            length(range.key), " ", change.var, " values \n",
            sep = ""))
  
  # create temp data
  newX <- X
  
  # replace change var value x
  newX[,change.var] <- range.key[[x]]
  
  # matrix multiplication for the systematic component
  sys.com <- as.matrix(tcrossprod(as.matrix(newX), beta.draws))
  
  # add RE
  lp <- sys.com + z.b
  
  # average over observations for each draw
  ev <- as.data.frame(lp) %>%
    summarise_all(list(mean))
  
  # add set identifier
  sim.out <- ev %>%
    gather(draw, ev) %>%
    mutate(setx = range.key[[x]],
           draw = str_replace_all(draw, "V", ""))
  
  return(sim.out)
})

# calculate expected value 
ev.gdp.pc <- sim.out.gdp.pc %>%
  group_by(setx) %>%
  summarize(mean = mean(ev, na.rm = TRUE),
            lwr = quantile(ev, probs = 0.025),
            upr = quantile(ev, probs = 0.975))

# get distribution data
dist.fm <- fm@frame

# clean distribution data
dist.fm <- dist.fm %>%
  filter(`log(gdp_pc_const_lag)` <= max(range.key)) %>%
  mutate(setx = `log(gdp_pc_const_lag)`)

# set parameters
axis.title.size <- 14
ribbon.alpha <- 0.1

# plot upper panel
p.ev.gdp.pc <- ggplot(ev.gdp.pc,
                   aes(x = setx, 
                       y = mean)) +
  geom_ribbon(aes(ymin = lwr,
                  ymax = upr),
              alpha = ribbon.alpha) +
  geom_line(size = 0.4) +
  geom_vline(xintercept = mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) -
               sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) + 0.3355,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) + 0.296,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) +
               sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) + 0.256,
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  scale_x_continuous("Log Constant GDP Per Capita (2010 USD, lag)") +
  scale_y_continuous("Predicted Level of Emerging Market's Capital Outflow Restrictions") +
  theme_bw() +
  theme(plot.title = element_text(size = axis.title.size + 1,
                                  face = "bold",
                                  margin = margin(0, 0, 20, 0),
                                  hjust = 0.5),
        axis.title.x = element_text(size = axis.title.size,
                                    margin = margin(20, 0, 0, 0)),
        axis.title.y = element_text(size = axis.title.size - 3,
                                    margin = margin(0, 20, 0, 0)),
        strip.text = element_text(size = axis.title.size + 2),
        plot.margin = margin(1, 0.2, -1.7, 0.4, unit = "cm"),
        strip.background = element_blank(),
        panel.grid.minor = element_blank(),
        legend.justification = "top")

p.ev.gdp.pc

# set annotation text shift
anot.m.shift <- 0.05

# plot bottom panel
p.marginal.gdp.pc <- ggplot(dist.fm, 
                         aes(x = setx, y = ..density..)) + 
  geom_density(alpha = .5,
               fill = "blue") + 
  geom_vline(xintercept = (mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) -
                             sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE)),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  geom_vline(xintercept = (mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) +
                             sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE)),
             size = 0.4,
             color = I(hsv(0/12, 7/12, 7/12)), 
             linetype = "dashed") +
  scale_x_continuous("Log Constant GDP Per Capita (2010 USD, lag)") +
  scale_y_continuous("Density \n",
                     breaks = seq(0, 0.8, 0.2),
                     labels = format(seq(0, 0.8, 0.2),
                                     nsmall = 1,
                                     scientific = FALSE),
                     limits = c(0, 0.8)) +
  theme_bw() +
  theme(legend.position = c(0.922, 0.76),
        legend.key.height = unit(0.01, "cm"),
        legend.key = element_rect(fill = "transparent", 
                                  colour = "transparent",
                                  size = 0.1),
        legend.title = element_text(size = axis.title.size - 6), 
        axis.title.x = element_text(size = axis.title.size, 
                                    margin = margin(20, 0, 0, 0)),
        axis.title.y = element_text(size = axis.title.size - 3, 
                                    margin = margin(0, 8.045, 0, 0)),
        strip.text = element_text(size = 0),
        strip.background = element_blank(),
        plot.margin = margin(0, 0.2, 0.2, 0.4, unit = "cm"),
        panel.grid = element_blank()) + 
  annotate("text", 
           x = mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) + anot.m.shift, 
           y = 0.7, 
           label = "mean",
           hjust = 0) +
  annotate("text", x = (mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) +
                          sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE)) + anot.m.shift, 
           y = 0.7, 
           label = "+1 s.d.",
           hjust = 0) +
  annotate("text", x = (mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) -
                          sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE)) + anot.m.shift, 
           y = 0.7, 
           label = "-1 s.d.",
           hjust = 0)

p.marginal.gdp.pc

# save
pdf(file = paste(MAIN_DIR, "Fig-C.4.pdf", sep = "/"), 
    width = 7, height = 7)
grid.arrange(p.ev.gdp.pc, p.marginal.gdp.pc, 
             ncol = 1, 
             heights = c(2, 0.8))
dev.off()

# check DV sd
summary(sim.df$kao)
sd(sim.df$kao)

# mean
mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE)
# mean - 1sd
mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) - sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE)
# mean + 1sd
mean(log(sim.df$gdp_pc_const_lag), na.rm = TRUE) + sd(log(sim.df$gdp_pc_const_lag), na.rm = TRUE)

# increase log gdp from 1 sd below mean to above, KAO decreases by approx. 0.61 (1.56 sd)
ev.gdp.pc[38, "mean"] - ev.gdp.pc[14, "mean"]
(ev.gdp.pc[38, "mean"] - ev.gdp.pc[14, "mean"])/sd(sim.df$kao)

